2011-08-21 83 views
1

我想验证我的文本文件是否已经包含用户在文本字段中输入的单词。当用户点击验证,如果单词已经在文件中,用户将输入另一个单词。如果单词不在文件中,则会添加单词。我的文件的每一行都包含一个单词。我把System.out.println看到正在打印什么,它总是说这个词不存在于文件中,但它不是真的......你能告诉我什么是错的吗?(JAVA)比较用户输入的单词与文本文件中包含的另一个单词

谢谢。

class ActionCF implements ActionListener 
    { 

     public void actionPerformed(ActionEvent e) 
     { 

      str = v[0].getText(); 
      BufferedWriter out; 
      BufferedReader in; 
      String line; 
      try 
      { 

       out = new BufferedWriter(new FileWriter("D:/File.txt",true)); 
       in = new BufferedReader(new FileReader("D:/File.txt")); 

       while ((line = in.readLine()) != null) 
       { 
        if ((in.readLine()).contentEquals(str)) 
        { 
         System.out.println("Yes"); 

        } 
        else { 
         System.out.println("No"); 

         out.newLine(); 

         out.write(str); 

         out.close(); 

        } 

       } 
      } 
      catch(IOException t) 
      { 
       System.out.println("There was a problem:" + t); 

      } 
     } 

    } 
+0

哪些内容Ø f您正在使用的文件,您的输入是什么,控制台吐出了什么? –

+0

您是否尝试过使用扫描仪?我总是比较喜欢扫描仪。 – buch11

+0

嗨尼古拉斯。每行文本文件包含1个字。用户在textField中输入一个单词,并且我想知道这个单词是否已经在文本文件中,如果没有,请添加它。 – ARH

回答

6

它看起来像你打电话in.readLine()两次,一次是在while循环并且再次在有条件的。这导致它跳过每隔一行。此外,您要使用String.contains而不是String.contentEquals,因为您只是检查行是否包含这个词。此外,您希望等到整个文件已被搜索,然后再决定找不到该单词。所以,试试这个:

//try to find the word 
BufferedReader in = new BufferedReader(new FileReader("D:/File.txt")); 
boolean found = false; 
while ((line = in.readLine()) != null) 
{ 
    if (line.contains(str)) 
    { 
     found = true; 
     break; //break out of loop now 
    } 
} 
in.close(); 

//if word was found: 
if (found) 
{ 
    System.out.println("Yes"); 
} 
//otherwise: 
else 
{ 
    System.out.println("No"); 

    //wait until it's necessary to use an output stream 
    BufferedWriter out = new BufferedWriter(new FileWriter("D:/File.txt",true)); 
    out.newLine(); 
    out.write(str); 
    out.close(); 
} 

(从我的例子中省略异常处理)

编辑:我只是重新阅读您的问题 - 如果每行只包含一个字,然后equalsequalsIgnoreCase会工作,而不是的contains,确保呼吁linetrim测试之前,过滤掉任何空白:

if (line.trim().equalsIgnoreCase(str)) 
... 
+1

另一件值得指出的事情是,如果文件包含两行不是输入的单词,第一行将关闭“BufferedWriter”,第二行将抛出异常(导致while循环终止),如它会试图写入一个关闭的'BufferedWriter'。 –

+0

@nicholas - 是的,编辑我的答案来涵盖这个问题。 –

+0

非常感谢您的帮助! :-) – ARH

相关问题