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

2023/2/17

How to Append Text to an Existing File in Java

Niru Niru

2023/2/17

#
I need the code to write without destroying the current data in the file. I want to store my scores in the file, after every game the score needs to be scored in the Highscore file. My current problem is that after every game the file rewrites, I don't want that.
public void read()
   { 
      File file = new File("C:/Users/nnnvi/Documents/Greenfoot copy/CricketGame-copy/Highscore.txt");
      try
      {
         lines = Files.readAllLines(file.toPath());
      }
      catch(IOException e)
      {
         System.err.println("An exception occurred");
      }
      theLines = lines.toArray(new String[0]);
      
   }
   public void write()
   {
      try
      {
          String text = Integer.toString(myScore);
          Path fileName = Path.of("C:/Users/nnnvi/Documents/Greenfoot copy/CricketGame-copy/Highscore.txt");
          Files.writeString(fileName, text);
      }catch(IOException e)
      {
          System.err.println("An exception occurred");
      }
   }
Spock47 Spock47

2023/2/18

#
You can give the writeString method additional arguments to define how the file is opened. The default is that it "overrides" the file content. By adding the option "APPEND", it will instead append the new text at the end of the file. So, please change line 21 to the following and check whether it works as you want:
Files.writeString(fileName, text, StandardOpenOption.APPEND);
Note: Propably you will have to add the following import statement at the top of your source code:
import java.nio.file.StandardOpenOption;
Live long and prosper, Spock47
Niru Niru

2023/2/18

#
Spock47 wrote...
You can give the writeString method additional arguments to define how the file is opened. The default is that it "overrides" the file content. By adding the option "APPEND", it will instead append the new text at the end of the file. So, please change line 21 to the following and check whether it works as you want:
Files.writeString(fileName, text, StandardOpenOption.APPEND);
Note: Propably you will have to add the following import statement at the top of your source code:
import java.nio.file.StandardOpenOption;
Live long and prosper, Spock47
Thank you.
You need to login to post a reply.