我想验证我的文本文件是否已包含用户在文本字段中输入的单词。当用户单击“验证”时,如果该单词已存在于文件中,则用户将输入另一个单词。如果该单词不在文件中,则会添加该单词。我文件的每一行都包含一个单词。我把System.out.println放在看看正在打印的内容上,它总是说文件中没有这个词,但它不是真的......你能告诉我什么是错的吗? / p>
感谢。
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 :(得分: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();
}
(我的例子省略了异常处理)
编辑:我刚刚重新阅读了您的问题 - 如果每一行只包含一个字,则equals
或equalsIgnoreCase
将起作用,而不是contains
,确保在测试line
之前调用trim
,以过滤掉任何空格:
if (line.trim().equalsIgnoreCase(str))
...