小编Nar*_*mer的帖子

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

我想将文本写到文件中,每次这样做都应该换一行。我已经看到这个问题的许多答案只是“使用\ 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();
        }
Run Code Online (Sandbox Code Playgroud)

我编写的代码在文件中写入了新的Highscore和创建者的姓名。它的工作原理非常好,除了它可以将所有内容写在这样的行上,例如:Nicola:您的高分是10秒Thomas:您的高分是11秒,但我想要:Nicola:您的高分是10秒Thomas:您的高分是11秒

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

java string file line-breaks

1
推荐指数
2
解决办法
72
查看次数

标签 统计

file ×1

java ×1

line-breaks ×1

string ×1