首页 > 解决方案 > 如何查找 BufferedReader 文件中是否存在一行?

问题描述

我在 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;
}

标签: javabufferedreader

解决方案


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

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;

推荐阅读