好的,所以我试图将多行字符串保存到文本文件中,而不会覆盖以前的文本。 println完美打印它,但保存到文本文件似乎只保存第一行。
到目前为止我所写的内容(写入没有覆盖,但只写第一行):
try {
FileWriter fileWriter = new FileWriter(FileManager.usernames, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(multilineString + "\n");
bufferedWriter.close();
}
catch(IOException e) {
e.printStackTrace();
}
答案可能很简单,但我是Java新手。
答案 0 :(得分:0)
你应该试试bufferedWriter.flush();
这是可以帮助你的代码片段
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteIntoFile {
public static void main(String[] args) {
String multilineString = "This is line 1\nthis is line 2\nthis is last line";
try {
FileWriter fileWriter = new FileWriter("multiline.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(multilineString + "\n");
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}