我想将文本写入文件,每次执行时都应该换一行。我看到这个问题的许多答案只是“使用\ 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;)

最佳答案

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

编辑

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

10-07 13:01
查看更多