写入文本文件时如何结束行?

How do I end line when writing to a text file?

我正在写入一个文本文件,但是当我查看该文件时,即使我在 for 循环的字符串中添加了“\n”,所有内容都在线。我忽略了什么?

File file = new File(dir.getAbsolutePath() + "\SavedJavaArithmetic.txt");

FileWriter fileW = new FileWriter(file);
BufferedWriter buffW = new BufferedWriter(fileW);

for (int i = 0; i < list.size(); i++) {
    buffW.write(list.get(i).toString() + "\n");
}
buffW.close();
fileW.close();

数组列表 "list" 已经在 for 循环开始时创建并填充。

请编程到List界面。对于你的问题,使用 System.lineSeparator(), because "\n" is not cross-platform (on Windows, the line separator is "\r\n"). Next, File provides two argument constructors. And there is BufferedWriter.newLine() 可能看起来像

List<String> list = new ArrayList<>();
File file = new File(dir.getAbsolutePath(), "SavedJavaArithmetic.txt");

try (FileWriter fileW = new FileWriter(file);
            BufferedWriter buffW = new BufferedWriter(fileW)) {
    for (int i = 0; i < list.size(); i++) {
        buffW.write(list.get(i));
        buffW.newLine();
    }
}

或者,使用 PrintWriter(它提供更自然的语法)。而且,我会使用 for-each 循环。 还有,在这两种情况下,我都会使用 try-with-resources 来处理 close(s)。把它们放在一起可能看起来像,

List<String> list = new ArrayList<>();
// ...
File file = new File(dir.getAbsolutePath(), "SavedJavaArithmetic.txt");
try (PrintWriter pw = new PrintWriter(file)) {
    for (String str : list) {
        pw.println(str);
    }
}

,在Java 8+中,使用StreamforEachOrdered like

List<String> list = new ArrayList<>();
File file = new File(dir.getAbsolutePath(), "SavedJavaArithmetic.txt");
try (PrintWriter pw = new PrintWriter(file)) {
    list.stream().forEachOrdered(pw::println);
}