我在使用 BufferedReader 时遇到了非常奇怪的行为。我想读取整个文件,但它只读取每隔一行。
例如下面的文件
1 //ignore the left most space - shouldn't exist
2
3
4
5
6
将输出
2
4
6
这是我的一些代码...
fileRead = new BufferedReader(new InputStreamReader( new FileInputStream(file)));
public void scan(){
if (fileRead != null){
try{
while ((fileRead.readLine()) != null){
String line = fileRead.readLine();
String abcLine = line;
System.out.println(line);
}
}catch(IOException e) {
System.out.println("Line can not be read");
}
}else{ System.out.println("Can not Read - File Not Found"); }
}
我最好的选择是 bug 存在于 while 语句中。这是确保的正确方法吗 您读取文件直到到达 EOF“文件结尾”吗?
任何见解都会受到真正的赞赏
谢谢!
最佳答案
您每次循环都会读取两行。您当前的代码是:
while ((fileRead.readLine()) != null){ // reads a line, ignores it
String line = fileRead.readLine(); // reads another line, stores in 'line'
... // do stuff with 'line'
}
每次调用readLine()
都会读取一行。您可能想要更多类似的东西:
String line;
while ((line = fileRead.readLine()) != null) {
... // do stuff with 'line'
}
关于java - 意外的缓冲读取器行为 : skipping odd-numbered lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751190/