gpt4 book ai didi

java - 打印文本文件的行时,阅读器返回每行之间的行间距

转载 作者:行者123 更新时间:2023-12-02 03:55:20 24 4
gpt4 key购买 nike

我想从文本文件中检索行,如下所示:

line one
line two
line three

但输出是这样的:

line one
space line
line two
space line
line three

这是我的代码:

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/users/Moath Ibrahem/Desktop/Questions.txt"));
System.out.println(br.readLine());
System.out.println(br.readLine());
System.out.println(br.readLine());
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

最佳答案

我认为您的文件中存在空白行,并且由于您正在阅读和打印所有内容,因此它也会打印空白行。

如果您想避免打印空行,则可以在打印之前检查空行。

这是更正后的代码片段:

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/users/Moath Ibrahem/Desktop/Questions.txt"));
String str = br.readLine();
if(!str.equals("")) {
System.out.print(str);
}
/* Repeat */
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

输出:

line one
line two
line three

关于java - 打印文本文件的行时,阅读器返回每行之间的行间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528214/

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