elw*_*ynn 2 java string search text file
我需要在由几行字符串组成的文本文件中的特定行上找到一个字符串.但是,我找到文本或文件末尾的循环是永久搜索.我知道字符串在文件中.这是我用来查找文本的代码 - 但要注意,如果你在系统上尝试它,即使是一个简单的文本文件,它也会进入一个永恒的循环.
我非常感谢任何提示或指示来解释我在这里做错了什么.
private static void locateText(String locateText, BufferedReader locateBffer) {
boolean unfound = true;
try
{
String line = locateBffer.readLine();
while (unfound)
{
line = locateBffer.readLine();
if ((line.equals(locateText)) || (line == null))
{
unfound = false;
}
}
}
catch(IOException e)
{
System.out.println("I/O error in locateText");
}
}
Run Code Online (Sandbox Code Playgroud)
更新:发现问题 - 它没有在文件的第一行找到匹配项.
我认为GaryF是对的(您的文本位于文件的第一行).
我想在你的代码中指出一行:
if ((line.equals(locateText)) || (line == null)) {
Run Code Online (Sandbox Code Playgroud)
你必须写这个:
if ((line == null) || (line.equals(locateText)) {
Run Code Online (Sandbox Code Playgroud)
实际上,如果line为null,则代码将抛出NullPointerException.这就是为什么你必须测试,如果line是null前.
除此之外,我建议您查看Apache的commons.lang库,因为它为文本提供了非常有用的类(如StringUtils)...