Nar*_*mer 1 java string file 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();
}
Run Code Online (Sandbox Code Playgroud)
我编写的代码在文件中写入了新的Highscore和创建者的姓名。它的工作原理非常好,除了它可以将所有内容写在这样的行上,例如:Nicola:您的高分是10秒Thomas:您的高分是11秒,但我想要:Nicola:您的高分是10秒Thomas:您的高分是11秒
我知道我还需要修复和改进一些其他东西,但是现在,这是我最大的问题。有谁知道该怎么办?(对不起,我叫btw;)
您需要做: out.write(System.getProperty("line.separator"));
System.getProperty("line.separator")
将为您的平台(无论Windows / Linux / ..)提供行分隔符。
Windows和Linux的换行符不同。试着写\r\n
。
编辑
如果System.lineSeparator()
用于获取换行符,它将提供基于平台的换行符。因此,如果您在Unix上创建文件并将其发送给Windows用户,他们将看到该文件就像一行一样。但是,如果您使用Windows操作系统创建文件,则Linux用户将看到文件正确。