这是我的代码。如果我输入 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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句