【发布时间】:2016-07-29 03:48:21
【问题描述】:
我目前正在开发一款游戏,我很难覆盖保存文件。我已经看到如何清除文件,然后稍后重写它,但我想要一些能够覆盖文件的东西。我正在使用 BufferedWriter 和 FileWriter 库。这是我正在使用的代码:
System.out.println("Congratulations! You beat the first maze! Thanks for playing!\nBefore you go, please answer this one question.");
System.out.println("Please enter a color of the following choices.\nBlack, Navy, Dark Gray, Gray, Light Gray, Purple, Olive, Pink, White, or\nYellow.");
String fave = kb.nextLine();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(newFile("colorchoice.txt"),true));
writer.write(fave);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception ex) { /*ignore*/ }
}
try {
writer.flush();
writer.setLength(0);
writer = new BufferedWriter(new FileWriter(new File("save.txt"), true));
writer.write(name);
writer.newLine();
writer.write(choice4);
writer.newLine();
if (choice == 1 || choice == 2) {
writer.write(gender2);
writer.newLine();
}
writer.write(col);
writer.newLine();
writer.write(dead2);
writer.newLine();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception ex) { /*ignore*/ }
}
System.exit(0);
忽略 println 语句,我可以在 BufferedWriter 或 FileWriter 中做些什么来覆盖文件吗?还是我需要更改对其他库的导入才能使覆盖工作?
感谢任何帮助。
【问题讨论】:
-
FileWriterconstructor 的第二个参数是append。您已将其设置为true,它将添加到文件中。
标签: java