[英]How to find if a line exists in the BufferedReader file?
我在 Java 中有这个方法,它在另一个方法的 try 块中调用。 importFormat 在 try 块中返回具有分配值的 class(//做需要的事情)。 该方法应该逐行读取文件。 如果对带有 try 块的方法的方法调用被调用的次数多于文件中的行数,importFormat() 应该返回 null。
我试图用 if 块检查它,虽然它做的不多并且总是返回 ClassName。 似乎 class 总是存储文件的第一行。
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;
}
我不太明白你的问题,但我认为你不应该这样比较:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.