【发布时间】: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