1

I'm modifying a 2048 game I found on the internet so that it will print out the last given score of a player when he loses or resets the game. However, I'm having a problem with saving all of the scores. It actually works, but the program overwrites the file each time the player resets or loses.

Here's my writer class.

class writer {
    public void writing(int desiredText) {
        try {
            //Whatever the file path is.
            File highScores = new File("C:/Users/Anthony/Desktop/Java/highScores.txt");
            FileOutputStream is = new FileOutputStream(highScores);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);

            String desiredText_string = Integer.toString(desiredText);
            w.write(desiredText_string);
            w.close();
        } catch (IOException e) {
        System.err.println("Problem writing to the file highScores.txt");
        }
    }
}

Just incase, this is the exact moment that the writer is needed.

public void keyPressed(KeyEvent e) {
   if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
write.writing(myScore);

resetGame();          
   }
if (!canMove()) {
   write.writing(myScore);

   myLose = true;
}

... (code is continued on...)

2 Answers2

3

If you don't want to overwrite but you want to append the new data at the end of the file here is how to proceed:

FileOutputStream is = new FileOutputStream(highScores, true);
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

Another solution (I'm not sure if better) is to create a new file each time a game ends:

Date date = new Date();
File highScores = new File("C:/Users/Anthony/Desktop/Java/highScore"+date+".txt");

Adding a time stamp at end of file name.

hcarrasko
  • 2,320
  • 6
  • 33
  • 45