最后一行不包含任何内容,但它不返回null
。代码如下
使用调试时Eclipse
,我line= ""
在调试模式下看到,如何防止这种情况发生
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
最后一行不包含任何内容,但它不返回null
。代码如下
使用调试时Eclipse
,我line= ""
在调试模式下看到,如何防止这种情况发生
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
您不阻止它发生,空行是一行,因此它将按原样返回。
您可以做的是在处理之前检查该行是否为空:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
// process the line.
}
}
br.close();
BufferedReader.readLine() 方法在到达文件末尾时返回 null。
您的程序似乎在到达文件末尾之前正在读取文件中的行。终止的条件是该行为空,空字符串不为空,因此它循环并且不会终止。
nulll = 没有。"" = 空。如果最后一行为空,则应为“”。以下行应为空。
从那里您可以测试是否为空(我喜欢 appache StringUtils isEmpty)或在处理之前从文件中删除最后一个 \n。
如果该行由单个换行符组成,line
将为空String
,但readLine
不会返回 null。readLine
仅在到达文件末尾时才返回 null 。