我想做的是保存游戏的所有得分,但似乎只是在覆盖第一行,而不是将它们添加到下一行。我需要你的帮助!预先谢谢你!
System.out.print("Enter Your Name: ");
String name = inputName.nextLine();
try {
File highscore = new File("highscore.txt");
PrintWriter output = new PrintWriter(highscore);
if (highscore.exists()) {
System.out.println("Score has been saved!");
}
output.println(name + " - " + score);
output.close();
} catch (IOException e) {
System.out.println(e);
}
}
答案 0 :(得分:1)
要以附加模式打开文件,必须使用FileWriter(String fileName, boolean appender)
构造函数。
output = new BufferedWriter(new FileWriter(file_name, true));
添加以上行,它应该可以工作。
答案 1 :(得分:1)
代替
output.println()
使用
output.append()
应该起作用...
答案 2 :(得分:1)
使用PrintWriter output = new PrintWriter(new FileWriter(highscore, true));
代替PrintWriter output = new PrintWriter(highscore);
由于构造函数中的第二个参数告诉FileWriter 将输入追加到文件中而不是覆盖它。
public class StreamFilter {
public static void main(String[] args) {
System.out.print("Enter Your Name: ");
Scanner inputName = new Scanner(System.in);
String score="hui";
String name = inputName.nextLine();
try {
File highscore = new File("highscore.txt");
PrintWriter output = new PrintWriter(highscore);//remove this
PrintWriter output = new PrintWriter(new FileWriter(highscore, true));//usethis,
if (highscore.exists()) {
System.out.println("Score has been saved!");
}
output.println(name + " - " + score);
output.close();
} catch (IOException e) {
System.out.println(e);
}
}
}