2013-04-01 85 views
1

我创建了一个Java游戏,当游戏结束时,会执行一个方法告诉用户输入他/她的名字,然后他们的分数将保存在playscores.txt文档中。这工作正常。但是,我想要的不仅仅是这个文档中的一个人的分数。我想要它,所以每个玩游戏名称和分数的人都会被保存在这个文档中。真的很感谢一些帮助。FileWriter,How to write on the same document

这是我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的可惜无法弄清楚如何做到这一点,并想知道如果它甚至有可能。此外,我想知道我应该使用什么类来完成这件事。

+0

也[这里](http://stackoverflow.com/questions/3005124/writing-to-an-already-existing-file-using-filewriter-java),还[此问题](http:// stackoverflow.com/questions/1616746/java-filewriter-overwrite?rq=1)。 –

+0

@HovercraftFullOfEels我发现我自己的帖子的创建者已经要求将其删除,因为有重复的帖子。 –

回答

1

如果你感到快乐,只是追加新的评分,以文件的末尾,取代:

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

有:

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

如果你能有一个以上的用户在玩同时,您还需要使用文件锁定功能,以避免访问文件时的竞争条件。

+0

谢谢Martin,从来不知道那是那么简单!不幸的是,我不能接受你的答案再过8分钟! –

+0

@JamesDanny:如果你接受他或不接受他,因为这个问题很可能会被重复。它只被问过几百次。 –

1

为了对多人进行操作,您应该以追加模式打开文件。

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

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

参数:

  • 文件 - 一个文件对象写入

  • 追加 - 如果为true,则将字节写入到文件末尾 rathe比开始。

默认情况下,追加参数为所以,早些时候,你用当前的球员覆盖了前一名球员的得分。

1

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

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

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

希望有所帮助。