缓冲读取器输出异常

4

我有这个简单的方法:

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行中所见,我包含了print以进行调试。我希望这个方法可以从这个txt文件中返回字符串:

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是从哪里来的? 最后返回的字符串似乎是空的。 我想了解这里发生了什么。谢谢 :)

5
每次调用readLine()都会读取一行新内容。在循环的每次迭代中,您正在读取3行内容。 - JB Nizet
1
最终,您应该在方法退出/返回时关闭FileReader。 - Matthias
4个回答

7
这是因为你在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中分配的变量表示从文件中读取的最后一行。

2

每个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

从你看到的内容中可以发现,你在使用很多行代码,但只输出了很少的内容。其他人已经提供了很好的解决方案来解决这个问题,因此本答案不再赘述。


0
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

0

好的,这里的问题是:每次调用 bufferedReader.readLine()时,实际上会每次读取一行,因此第一行在while中被读取并丢弃,第二行被System.out.println输出,第三行被写入文件,以此类推。您需要存储读取的第一行并使用它进行下一步操作,例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接