如何查找BufferedReader文件中是否存在一行?

问题描述 投票:-1回答:1

我在Java中使用了这个方法,它是在另一个方法的try块中调用的,importFormat在try块中返回带有赋值的类(/做需要的事情)。该方法应该逐行读取一个文件。如果调用带有try block的方法的次数比文件中的行数多,importFormat()应该返回null。

我试着用if block检查了一下,不过并没有什么作用,总是返回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()方法,但没有任何区别。

EDIT:我发现我重现的代码不正确,很抱歉。这里应该是比较清晰的最小可重现的代码。

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;
}
java bufferedreader
1个回答
-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;
© www.soinside.com 2019 - 2024. All rights reserved.