BufferReader 意外输出

BufferReader unexpected output

我有这个简单的方法:

private String read(String filePath) throws IOException {
    FileReader fileReader = new FileReader(filePath);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String fileContent = "";
    StringBuilder stringBuilder = new StringBuilder(fileContent);

    while (bufferedReader.readLine() != null){
        System.out.println(bufferedReader.readLine());
        stringBuilder.append(bufferedReader.readLine());
    }
    return fileContent;
}

正如您在第 8 行中看到的,我包含了用于调试目的的打印 我想用这个方法从这个 txt 文件 return 字符串:

1a1
2b 2a
3c 3b 3a
4d 4cr 4bb4 4a
5e 5d 5c 5b 5ax
6f 6ea 6d 6ca 6bb 6a
7g 7f 7ea

出于某种原因输出是这样的:

2b 2a
5e 5d 5c 5b 5ax
null

为什么只读到第二行和第五行? 这个 null 来自哪里? 末尾的字符串 returned 似乎是空的。

我想了解这里发生了什么。谢谢 :)

这是因为您在 while 循环的 null 检查中使用了每三行,打印从二开始的每三行,并附加从三开始的每三行,如下所示:

1  null check
2  print
3  append
4  null check
5  print
6  append
7  null check
8  print
9  append
... and so on

你应该将读到的行保存在一个String变量中,并在循环中使用它,如下所示:

String line;
while ((line = bufferedReader.readLine()) != null){
    System.out.println(line);
    stringBuilder.append(line);
}

现在循环头结合了赋值和null检查,从readLine赋值的变量表示从文件中读取的最后一行。

每个 readLine() 正在读取一个全新的行,为了分析发生了什么,让我们为每个 readLine() 调用命名。

while (bufferedReader.readLine() != null) {          // Read 1
    System.out.println(bufferedReader.readLine());   // Read 2
    stringBuilder.append(bufferedReader.readLine()); // Read 3
}

现在让我们将每个 readLine() 与其读取的行相关联:

1a1                   // Read 1 while loop condition
2b 2a                 // Read 2 this is when we print it
3c 3b 3a              // Read 3 append to stringBuilder
4d 4cr 4bb4 4a        // Read 1 while loop condition
5e 5d 5c 5b 5ax       // Read 2 this is when we print it
6f 6ea 6d 6ca 6bb 6a  // Read 3 append to stringBuilder
7g 7f 7ea             // Read 1 while loop condition
                      // Read 2 this is when we print it (null)
                      // Read 3 append to stringBuilder

如您所见,您消耗了很多行,而您只打印了几行。其他人已经指出了很好的解决方案来解决这个问题,因此这不在这个答案中。

好的,问题来了:你每次都调用bufferedReader.readLine(),这实际上是每次读取一个新行,所以第一行在while中读取并丢弃,第二行是System.out.println-ed,第三个写入文件等等。您需要存储读取的第一行并以此工作,例如:

for (String line = bufferedReader.readline(); line != null; line = bufferedReader.readLine()) {
    System.out.println(line);
    stringBuilder.append(bufferedReader.readLine());
}
1a1                   // Read 1 while (bufferedReader.readLine() != null) 
next 2a               // Read 2 System.out.println(bufferedReader.readLine()); --print
3c 3b 3a              // Read 3 stringBuilder.append(bufferedReader.readLine());-next