将字符串写入文件时如何换行?

时间:2019-05-05 18:20:43

标签: java string file javafx line-breaks

我想将文本写入文件,每次执行时都应该换一行。我看到这个问题的许多答案只是“使用\ n”,但这对我不起作用。

这是我使用的代码:

File file = new File("C:\\Users\\Schule\\IdeaProjects\\projectX\\src\\experiment\\input.txt");
        boolean result;
        if(!file.exists()) {
            try {
                // create a new file
                result = file.createNewFile();
                // test if successfully created a new file
                if(result) {
                    System.out.println("Successfully created " + file.getCanonicalPath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String output = name + ": " + highscoreString + "\n";
        try {
            PrintWriter out = new PrintWriter(new FileWriter(file, true));
            out.append(output);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

我编写的代码在文件中写入了新的Highscore和创建者的姓名。除了将所有内容写在这样的行上之外,它工作得很好,例如: 尼古拉:您的最高分是10秒托马斯:您的最高分是11秒 但是我想要: 尼古拉:您的最高分是10秒 托马斯:您的最高分是11秒

我知道我还需要修复和改进一些其他东西,但是现在,这是我最大的问题。有谁知道该怎么办? (对不起,我叫btw;)

2 个答案:

答案 0 :(得分:6)

您需要执行以下操作:out.write(System.getProperty("line.separator"));

System.getProperty("line.separator")将为您的平台(无论Windows / Linux / ..)提供行分隔符。

答案 1 :(得分:5)

Windows和Linux的换行符不同。尝试写\r\n

编辑

如果您使用System.lineSeparator()来换行,它将给出基于平台的换行符。因此,如果您在Unix上创建文件并将其发送给Windows用户,他们将看到该文件就像一行一样。但是,如果您使用Windows操作系统创建文件,则Linux用户将看到文件正确。