2

I am working on a project. For the project I am using GUI and I want to write a number to a file. I have been successful, and I can write the number to the file that i want to. My problem that hopefully someone can give insite to is that everytime i write a number to a file the new number replaces the old one. How would i go about keeping the current info in the file. My code is:

  public static void writeCodeFile (String filename, int x, String userName) throws IOException{
        BufferedWriter outputWriter = null;
        outputWriter = new BufferedWriter(new FileWriter(filename));
        outputWriter.newLine();
        outputWriter.write(userName +":"+ Integer.toString(x));
        outputWriter.newLine();
        outputWriter.flush();  
        outputWriter.close();   



}
sam.tldr
  • 65
  • 3
  • 9
toby1618
  • 23
  • 2

2 Answers2

3

Use append mode:

outputWriter = new BufferedWriter(new FileWriter(filename, true));
Mordechai
  • 15,437
  • 2
  • 41
  • 82
1

When you create the FileWriter, add a second parameter "true" to go into append mode.

DrC
  • 7,528
  • 1
  • 22
  • 37