2015-12-12 233 views
2

如何在正確的位置以降序將highscore追加到highscore.txt文件中?該方法使用先前創建的readHighScore(int score)方法來查找記錄應插入的行號。這是我走到這一步:如何在java中追加文件

public static void recordHighScore(String name, int score){ 
      File file = new File("Test/highscore.txt"); 
      FileWriter fwriter = new FileWriter(file, true); 
      try{ 
       String userName = name+","+score; 
       fwriter.add(readHighScore(score), userName); 

      }catch(IOException io){ 
       System.out.println("Missing File!"); 

      } 

      /*Writes the high score into highscore.txt file, at the correct position (in descending order). This 
      method uses readHighScore() method to find the line number where the record should be 
      inserted.*/ 
     } 
+0

要附加到文件的中間文件或結束了嗎? –

+0

我認爲它應該是前10名,所以也許文件的結尾?我不確定。 – zk9

+0

如果您不需要文件頂部的舊信息,那麼將數據讀入內存,更改內存中的信息並再次保存會很容易。 –

回答

0

它,如果你想在年底追加的數據很容易,如果你想在中間添加數據幾乎是不可能的。很容易讀取內存中的所有文件,將其更改並再次保存所有文件,覆蓋舊的信息。

例如:

// read file to arraylist 
Scanner s = new Scanner(new File("filepath")); 
List<Score> list = new ArrayList<Score>(); 
while (s.hasNext()){ 
    String[] a = s.next().split(","); 
    list.add(new Score(a[0], a[1]);); // Score is class with name and score fields 
} 
s.close(); 

// working with List<Score> 
// add new score to List<Score> 
// save List<Score> to file like in your code 
+0

你是如何做到的? – zk9

+0

我在我的帖子中添加示例 –

+0

謝謝,這非常有幫助 – zk9