gpt4 book ai didi

java - 在Java中逐行读取文本文件

转载 作者:行者123 更新时间:2023-11-30 10:46:13 25 4
gpt4 key购买 nike

如何逐行读取文本文件中的内容?当我尝试输出内容时,换行符似乎被忽略了。

public class ReadFile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String str= "";

//Reading content from file
Scanner in = new Scanner(new FileReader("text.txt"));
while(in.hasNextLine()){
str = str + in.nextLine();
str.concat("\n"); //Not working!!!!!!!!!!!
}

in.close();

//Writing content to another file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
out.println(str);
out.close();
}
}

最佳答案

您在以下行中犯了错误:

str.concat("\n"); 

更新如下:

str = str.concat("\n"); 

我正在提供更新的程序。

public class ReadFile {

public static void main(String[] args) throws IOException {
try (PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
Scanner in = new Scanner(new FileReader("text.txt"));) {
while (in.hasNextLine()) {
out.println(in.nextLine());
}
}
}
}

关于java - 在Java中逐行读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36673602/

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