【问题标题】:Rewriting files with BufferedWriter and FileWriter libraries使用 BufferedWriter 和 FileWriter 库重写文件
【发布时间】: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 中做些什么来覆盖文件吗?还是我需要更改对其他库的导入才能使覆盖工作?

感谢任何帮助。

【问题讨论】:

  • FileWriter constructor 的第二个参数是append。您已将其设置为 true,它将添加到文件中。

标签: java


【解决方案1】:
writer = new BufferedWriter(new FileWriter(newFile("colorchoice.txt"),true));

append 参数中将true 更改为false

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多