为什么if (txtLine == null) { break; };
不起作用?或者正确的答案是为什么它仍然将字符串txtLine
设置为null(字面意思)。我理解它的方式,它应该打破字符串为空的时刻?我不希望它将字符串设置为“null”。但是当* .txt文件中没有更多行时停止
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
if(txtLine == null){
break;
};
txtLine = txtReader.readLine();
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
txtFile
变量被定义为IVAR
private int nChars = 0;
private String txtLine = new String();
private ArrayList <String> array = new ArrayList <String>();
答案 0 :(得分:4)
我认为当你中断时以及当你将txtLine
的值更改为从文件中读取的下一行的顺序是向后的时候,你的代码应该类似于:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
txtLine = txtReader.readLine();
// check after we read the value of txtLine
if(txtLine == null){
break;
}
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
但这是一种更简洁(我认为更清晰)的形式:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while ((txtLine = txtReader.readLine()) != null) {
// Reads one line.
println(txtLine);
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
while ((txtLine = txtReader.readLine()) != null)
将txtLine设置为下一行,然后在继续之前检查txtLine是否为null。