【发布时间】:2019-09-23 11:43:40
【问题描述】:
我想将文本写入文件,每次我这样做时都应该换行。我已经看到这个问题的许多答案只是“使用 \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 秒 但我想要: Nicola:你的高分是 10 秒 托马斯:你的高分是 11 秒
我知道还有一些其他的事情需要修复和改进,但现在,这是我最大的问题。有谁知道该怎么做? (对不起我的名字顺便说一句;)
【问题讨论】:
-
\n是 Unix 风格的行尾。 Windows 样式为\r\n。几乎所有编辑器都接受这两种格式,但我猜你是在记事本中查看文件:) -
PrintWriter的文档应该会有所帮助:println(而不是append())- 您已经在使用System.out.println(...)中的类似 - 所以无需知道这在哪个操作系统上运行既不使用"\n" -
这里的
exists()/createNewFile()code 完全是浪费时间和空间。new FileWriter()已经做到了这一切。你强迫它发生两次。 -
它是纯 java,看起来与 fx 无关
标签: java string file line-breaks