【问题标题】:FileWriter, How to write on the same document [duplicate]FileWriter,如何在同一个文档上写入 [重复]
【发布时间】:2013-03-23 00:58:37
【问题描述】:

我创建了一个 Java 游戏,当游戏结束时,会执行一个方法,告诉用户输入他/她的姓名,然后他们的分数将保存在 playcores.txt 文档中。这工作正常。但是,我想要的不仅仅是一个人在本文档中的分数。我想要它,以便所有玩游戏名称和分数的人都将保存在此文档中。非常感谢您的帮助。

这是我的gameComplete方法代码:

public void gameComplete() throws IOException {
    String name = (String) JOptionPane.showInputDialog(
            frame,
            "Enter your name: ",
            "Save Score",
            JOptionPane.PLAIN_MESSAGE);
    Score score = new Score(player.getScore(), name);
    FileWriter fstream = new FileWriter("playerscores.txt");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("Name : " + score.getName() + System.getProperty( "line.separator" )  );
    out.write("Score : " + score.getScore());
    out.close();
}

我尝试了不同的东西,例如 Objectoutputstream,但不幸的是无法弄清楚如何做到这一点,并且想知道它是否可能。此外,我想知道我应该使用什么类来完成这项工作。

【问题讨论】:

  • 还有here,还有this question
  • @HovercraftFullOfEels 我们明白我自己的观点,帖子的创建者要求删除它,因为有重复的帖子。

标签: java netbeans


【解决方案1】:

如果您愿意将新乐谱附加到文件末尾,请替换:

FileWriter fstream = new FileWriter("playerscores.txt");

与:

FileWriter fstream = new FileWriter("playerscores.txt", true);

如果您可以让多个用户同时玩,您还需要使用文件锁定,以避免访问文件时出现竞争条件。

【讨论】:

  • 谢谢你,马丁,从来不知道这么简单!很遗憾,再过 8 分钟,我无法接受您的回答!
  • @JamesDanny:你是否接受他并不重要,因为这个问题很可能会作为重复而关闭。以前只被问过数百次。
【解决方案2】:

要为多人使用,您应该以附加模式打开文件。

FileWriter fstream = new FileWriter("playerscores.txt",true);

语法: public FileWriter(File file, boolean append)

参数:

  • file - 要写入的 File 对象

  • append - 如果为真,则字节将被写入文件末尾 而不是开始。

默认情况下,append 参数为 false所以,早些时候,你用当前的分数覆盖了前一个玩家的分数。

【讨论】:

    【解决方案3】:

    首先,如果您希望每次都添加文件而不是擦除和写入文件,请确保添加第二个参数 true 以使其附加文本。

    您可以使用 CSV 文件将答案存储在列中,然后使用逗号将其读出并解析数据。

    FileWriter fileW = new FileWriter("playerscores.txt", true);

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2014-03-13
      • 2011-12-21
      • 2018-03-06
      • 2020-09-29
      • 2020-07-15
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多