简体   繁体   English

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

[英]How can I make a line break when writing a string to a file?

I want to write text into a file and everytime I do it should make a new line. 我想将文本写入文件,每次执行时都应该换一行。 I've seen many answers to this question being just "use \\n" but that doesn't work for me. 我看到这个问题的许多答案只是“使用\\ n”,但这对我不起作用。

This is the code I used: 这是我使用的代码:

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();
        }

The code I have writes the new Highscore and the name of the person who made it in a file. 我编写的代码在文件中写入了新的Highscore和创建它的人的名字。 It works perfectly fine except that it writes everything on a line like this for example: Nicola: Your highscore is 10 secondsThomas: Your highscore is 11 seconds But I want: Nicola: Your highscore is 10 seconds Thomas: Your highscore is 11 seconds 它工作得非常好,除了它在这样的行上写所有内容,例如:Nicola:您的高分是10秒Thomas:您的高分是11秒,但我想要:Nicola:您的高分是10秒Thomas:您的高分是11秒

I know there are some other things I need to fix and improve but right now, this is my biggest problem. 我知道我还需要修复和改进一些其他东西,但是现在,这是我最大的问题。 Does anyone know what to do? 有谁知道该怎么办? (sorry for my name btw ;) (对不起,我叫btw;)

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

System.getProperty("line.separator") will give you the line separator for your platform (whether Windows/Linux/..). System.getProperty("line.separator")将为您的平台(无论Windows / Linux / ..)提供行分隔符。

Windows and Linux line breaks are different. Windows和Linux的换行符不同。 Try to write \\r\\n . 尝试写\\r\\n

EDIT 编辑

If you use System.lineSeparator() to get line break it will give platform based line break. 如果使用System.lineSeparator()获取换行符,它将提供基于平台的换行符。 So if you create a file on unix and send it to windows users they will see that file like one line. 因此,如果您在Unix上创建文件并将其发送给Windows用户,他们将看到该文件就像一行一样。 But if you are using windows os to create file it linux users will see file correct. 但是,如果您使用Windows OS创建文件,则Linux用户将看到文件正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM