2

How do I append the highscore into highscore.txt file at the correct position in descending order? The method uses readHighScore(int score) method created previously to find the line number where the record should be inserted. This is what I got so far:

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.*/
        }
zk9
  • 41
  • 5
  • You want to append to the end of file or in the middle of file? – Slava Vedenin Dec 12 '15 at 18:46
  • I think it should be the top 10 so maybe the end of the file? I'm not sure. – zk9 Dec 12 '15 at 18:48
  • If you don't need old information in top of file, it's much easy if you read data to memory, change information in memory and save again. – Slava Vedenin Dec 12 '15 at 18:53
  • 1
    see this: http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java – guillaume girod-vitouchkina Dec 12 '15 at 18:55
  • Do not use FileWriter. It does not allow you to specify the character coding to be used. This is 2015. Use Paths.get() and Files.newBufferedWriter(). – fge Dec 12 '15 at 19:56
  • One more thing: DO NOT, ever, try and replace the original contents of a file whose contents vary depending on the length of the record. Record the new contents in a new file, always. Then rename it to the original only if the write in the new file has succeeded. – fge Dec 12 '15 at 20:16

1 Answers1

0

It's very easy if you want to append data at the end, and almost impossible if you want append data at the middle. Much easy read all file in memory, change it and save all file again, overwriting old informaton.

For example:

// 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
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59