无法使PrintWriter工作

Nei*_*nes 0 java io printwriter

我正在为游戏创建一个保存游戏文件,但我PrintWriter只是覆盖了文件而不是我需要的数字.

这是代码:

public void fileWriter() throws FileNotFoundException {
    PrintWriter print = new PrintWriter(new File("C:\\Users\\john\\Desktop\\stats.txt"));
    print.print(String.valueOf(this.swordNumber) + " ");
    print.print(String.valueOf(this.shieldNumber) + " ");
    print.print(String.valueOf(this.monstersDefeated) + " ");
    print.print(String.valueOf(this.damageDealt));
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一切来打印这些变量,String.valueOf但它不起作用.

小智 5

您应该正确使用Java的资源try-catch块.即使抛出任何异常,这也会自动关闭流:

public void fileWriter() throws FileNotFoundException {
    File file = new File("C:\\Users\\john\\Desktop\\stats.txt");
    try (PrintWriter print = new PrintWriter(file)) {
        print.print(Integer.toString(swordNumber) + " ");
        print.print(Integer.toString(shieldNumber) + " ");
        print.print(Integer.toString(monstersDefeated) + " ");
        print.print(Integer.toString(damageDealt));
    }
}
Run Code Online (Sandbox Code Playgroud)

而且String.valueOf()我建议使用Integer.toString()而不是使类型转换更明显.