将字符串写入文件时如何换行?
How can I make a line break when writing a string to a file?
我想将文本写入文件,每次我这样做都应该换行。我看到这个问题的很多答案都是 "use \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();
}
我的代码在文件中写入了新的高分和制作者的名字。它工作得很好,除了它把所有的东西都写在一行上,例如:
尼古拉:你的最高分是 10 秒托马斯:你的最高分是 11 秒
但是我想要:
尼古拉:你的高分是 10 秒
托马斯:你的高分是11秒
我知道还有一些其他的事情我需要修复和改进,但现在,这是我最大的问题。有谁知道该怎么办?
(对不起,顺便说一下我的名字;)
Windows 和 Linux 换行符不同。尝试写\r\n
.
编辑
如果您使用 System.lineSeparator()
获取换行符,它将给出基于平台的换行符。因此,如果您在 unix 上创建一个文件并将其发送给 windows 用户,他们将看到该文件就像一行。但是,如果您使用 windows os 创建文件,linux 用户将看到正确的文件。
您需要做:out.write(System.getProperty("line.separator"));
System.getProperty("line.separator")
将为您提供适合您平台的行分隔符(无论是 Windows/Linux/..)。
我想将文本写入文件,每次我这样做都应该换行。我看到这个问题的很多答案都是 "use \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();
}
我的代码在文件中写入了新的高分和制作者的名字。它工作得很好,除了它把所有的东西都写在一行上,例如: 尼古拉:你的最高分是 10 秒托马斯:你的最高分是 11 秒 但是我想要: 尼古拉:你的高分是 10 秒 托马斯:你的高分是11秒
我知道还有一些其他的事情我需要修复和改进,但现在,这是我最大的问题。有谁知道该怎么办? (对不起,顺便说一下我的名字;)
Windows 和 Linux 换行符不同。尝试写\r\n
.
编辑
如果您使用 System.lineSeparator()
获取换行符,它将给出基于平台的换行符。因此,如果您在 unix 上创建一个文件并将其发送给 windows 用户,他们将看到该文件就像一行。但是,如果您使用 windows os 创建文件,linux 用户将看到正确的文件。
您需要做:out.write(System.getProperty("line.separator"));
System.getProperty("line.separator")
将为您提供适合您平台的行分隔符(无论是 Windows/Linux/..)。