【问题标题】:How to find if a line exists in the BufferedReader file?如何查找 BufferedReader 文件中是否存在一行?
【发布时间】:2020-06-09 12:00:01
【问题描述】:

我在 Java 中有这个方法,它在另一个方法的 try 块中调用。 importFormat 在 try 块中返回具有分配值的类(//做需要的事情)。该方法应该逐行读取文件。如果对带有 try 块的方法的方法调用被调用的次数多于文件中的行数,则 importFormat() 应返回 null。

我尝试用 if 块检查它,虽然它没有做太多并且总是返回 ClassName。似乎该类总是存储文件的第一行。

private ClassName importFormat(BufferedReader br) throws IOException, ParseException {

String out;
Track t = new ClassName();

if((out = br.readLine()) == null) return null;

    //do what is needed

    }else{
        t = null; //here I unsuccessfully tried to force the method to again return null, no luck
        System.err.print(out);
        throw new ParseException("", 0);
    }

return t;

}

我也尝试过 br.ready() 方法,没有任何区别

编辑:我注意到我错误地复制了代码,对此我深表歉意。这里应该更清楚 最少的可重现代码:

private ClassName foo(BufferedReader br) throws IOException {
    ClassName t = new ClassName();
    String out = null;

    out = br.readLine();
    if(out.equals(null)) return null; //handle the case where there's no more line to read

    if(/*!string red from BufferedReader.isEmpty()*/){
        //do something
    }else{
        t = null; //ensure that null would be returned
        //do something more unrelated to this question
    }
    return t;
}

【问题讨论】:

  • Err,所以你想做“ if(x) then return null else return null”?请先考虑一下。不要试图用代码解决你的问题。首先解决您“头脑中”的问题。了解您想要解决的问题,以及如何解决。然后尝试在代码中写下解决方案。
  • 并注意:将您的关注点分开。例如,首先将整个文件读入内存,然后将其作为字符串列表传递可能更有意义。
  • 如果 br.readLine() 返回 null,则方法 importFormat() 返回 null。如果 br.readLine() 返回 null,则方法 importFormat() 将引发异常。因此,方法importFormat()的最后一行,即return t,是死代码。该行将永远被执行。也许您应该考虑发布minimal reproducible example
  • 再次:minimal reproducible example。你的代码没有做你认为它应该做的事情。但是您不是向我们展示您的代码,而是您认为它应该做什么。再说一遍:除非您允许我们这样做,否则我们无法帮助您。是的,这可能需要时间。但是您希望其他人利用空闲时间来帮助您解决问题。因此,请您花时间让我们为您提供帮助。它首先阅读你现在已经给出了三遍的那个链接。第二件事仍然伴随着你的假设。然后:不要只是添加到您的问题中。扔掉没有意义的东西。
  • 并且只是为了记录:你明白上面的代码只会读取第一行,然后返回吗?你没有循环,因此 readLine() 只被调用一次,因此它只读取第一行(取决于如何调用该方法?!)。

标签: java bufferedreader


【解决方案1】:

我不太明白你的问题,但我认为你不应该这样比较:

if((out = br.readLine()) == null) return null;

要在 java 中比较字符串,让我们使用 str1.equals(str2) 代替。所以我觉得你应该试试:

if(out.equals(br.readLine())) {
    //do sth here because "out" exists in BufferReader.
} else {
    System.out.println("Continue searching...\n");
}

return t;

【讨论】:

  • 我编辑了我的问题,并在使用 String#equals 时包含了您的建议。但是,它会产生相同的结果=整个方法从文件中返回有效行,即使它被调用的次数多于文件中的行数(在这种情况下,它应该返回 null,因为没有更多行可以读取)。
  • 还是很难理解。您不应该将 String 初始化为 null,可以将其初始化为空白,例如“”。如果要查找文件行中是否存在字符串,请尝试使用: br = new BufferedReader(new FileReader("D:\youFile.txt")); while ((out = br.readLine()) != null) { System.out.println(out); }
  • 在 while 循环中指定“out = br.readLine()”,确保它会读取文件中的所有行
猜你喜欢
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 2014-06-15
  • 2021-10-21
  • 2017-10-26
  • 2021-10-23
  • 2012-11-24
相关资源
最近更新 更多