(JAVA)将用户输入的单词与文本文件中包含的另一个单词进行比较

ARH*_*ARH 1 java file-io swing file awt

我想验证我的文本文件是否已包含用户在文本字段中输入的单词.当用户单击"验证"时,如果该单词已存在于文件中,则用户将输入另一个单词.如果该单词不在文件中,则会添加该单词.我文件的每一行都包含一个单词.我把System.out.println看看正在打印什么,它总是说文件中没有出现这个词,但事实并非如此......你能告诉我什么是错的吗?

谢谢.

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);

            }   
        }

    }
Run Code Online (Sandbox Code Playgroud)

Pau*_*ora 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();
}
Run Code Online (Sandbox Code Playgroud)

(我的示例中省略了异常处理)

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

if (line.trim().equalsIgnoreCase(str))
...
Run Code Online (Sandbox Code Playgroud)