gpt4 book ai didi

java - 如何检测文件中的新行(或空行)?

转载 作者:行者123 更新时间:2023-12-02 04:26:59 27 4
gpt4 key购买 nike

我正在尝试编写一个程序,该程序从用户指定的文件中读取文本。现在,该程序应该检测到空行。

这是我没有成功的尝试:

public static void editFile(String filePath) throws FileNotFoundException, IOException {
file = new File(filePath);
if(file.exists()) {
fileRead = new FileReader(file);

bufferedReader = new BufferedReader(fileRead);

String line = bufferedReader.readLine();
System.out.println(line);
while(line != null) {
line = bufferedReader.readLine();
if(line == "") {
//line = null;
System.out.println("a");
}
System.out.println(line);
}
}
}

更清楚地说:

如果我传递一个文本文件,例如包含以下文本:

test1
test2

test3

test4

由于有空格,它应该在控制台中打印 2 个 a,但事实并非如此。

感谢您的宝贵时间,我很高兴您提出任何建议。

最佳答案

这是因为比较错误。不能使用==来比较两个字符串,需要使用equals方法:

if(line.equals(""))

由于您正在检查空字符串,因此您也可以编写

if(line.isEmpty())

How do I compare strings in java?

关于java - 如何检测文件中的新行(或空行)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018367/

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