gpt4 book ai didi

java - BufferReader 意外输出

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:14 25 4
gpt4 key购买 nike

我有这个简单的方法:

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 来自哪里?最后返回的字符串似乎是空的。

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

最佳答案

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

关于java - BufferReader 意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com