java - 意外的缓冲读取器行为 : skipping odd-numbered lines

标签 java bufferedreader eof

我在使用 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/

相关文章:

java - 获取数字数组所有可能排列的 ArrayList

java - 尝试在 Spring Rest api 中上传文件时收到 415 不支持的媒体类型

Java BufferedReader

macos - git:EOF 处的新空行

python-2.7 - 尝试通过 Popen() 使用 Python 发送 EOF 信号(Ctrl+D)信号

java - 为什么 setVisibility() 在按下按钮后不使我的按钮和布局可见?

java - 在 maven 中导入 itext pdf 在 felix 控制台中无法解析

Java JSON - gson - 附加新数据,格式错误的 JSON

java - 如何使用 BufferedReader 将行放入 ArrayList 中然后执行它们?

linux - 我无法理解 sigaction() 结果