为什么 BufferedWriter 不写入文件中的所有行?
Why BufferedWriter doesn' write all lines in file?
这是我的代码。如果我输入 3 行文本,然后键入 "exit",它只会将最后一行文本写入文件。
我错过了什么?
谢谢
`public class WriteFile {
public static void writeFile() throws IOException {
Scanner sc = new Scanner(System.in);
String text;
File file = new File("file.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
while (!sc.nextLine().equalsIgnoreCase("exit")) {
text = sc.nextLine();
out.write(text);
out.newLine();
}
sc.close();
out.flush();
out.close();
}
}`
是的,你应该使用 append() 方法,删除最后插入的文本:
public static void writeFile() throws IOException {
Scanner sc = new Scanner(System.in);
String text = "";
File file = new File("file.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
while (!(text = sc.nextLine()).equalsIgnoreCase("exit")) {
out.append(text);
out.newLine();
}
sc.close();
out.flush();
out.close();
}
这是我的代码。如果我输入 3 行文本,然后键入 "exit",它只会将最后一行文本写入文件。 我错过了什么? 谢谢
`public class WriteFile {
public static void writeFile() throws IOException {
Scanner sc = new Scanner(System.in);
String text;
File file = new File("file.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
while (!sc.nextLine().equalsIgnoreCase("exit")) {
text = sc.nextLine();
out.write(text);
out.newLine();
}
sc.close();
out.flush();
out.close();
}
}`
是的,你应该使用 append() 方法,删除最后插入的文本:
public static void writeFile() throws IOException {
Scanner sc = new Scanner(System.in);
String text = "";
File file = new File("file.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
while (!(text = sc.nextLine()).equalsIgnoreCase("exit")) {
out.append(text);
out.newLine();
}
sc.close();
out.flush();
out.close();
}