This site requires JavaScript, please enable it in your browser!
Greenfoot back
tylermwise
tylermwise wrote ...

2022/12/15

Add text to txt instead of overwriting (FileWriter)

tylermwise tylermwise

2022/12/15

#
Hi there, I am trying to make it so every time the user dies, the score will be added into a text file. At the moment this file gets made, but when I replay the game it overwrites everything saved into it. I am wanting to make it, so it adds text onto the file, and you can look back at all the games instead of it overwriting...
        FileWriter fw = null;
        try
        {
            fw = new FileWriter("scores.txt", false);
            fw.write( Calendar.getInstance().getTime() + " | Score: " + score + " (" + lives + " Lives Left)" );
        }
        catch (Exception e){ e.printStackTrace(); }
        finally { if(fw != null) { try { fw.close(); } catch (Exception e) { e.printStackTrace(); } } }
Any help would be really appreciated, thanks!
Spock47 Spock47

2022/12/15

#
Looking at the documentation of FileWriter, it says that the boolean in the constructor determines whether it appends (or overrides), so change line 4 to the following and check whether it works:
fw = new FileWriter("scores.txt", true);
tylermwise tylermwise

2022/12/15

#
Oh! Thank you it works :)
You need to login to post a reply.