1
try {
                File file = new File(filePath+"usedcommands.txt");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(input+"\n");
                bw.close();
            } catch(Exception e) { System.out.println("can't write to usedcommands.txt..."); }

I'm writing to a txt file, but every time I run through the writing process it overrides what is already written there. How can I change my code so this part of the program doesn't override what is already there?

Arc
  • 441
  • 1
  • 9
  • 26

2 Answers2

3

Pass true as a second argument to FileWriter to turn on "append" mode.

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Lalit Chattar
  • 1,914
  • 8
  • 27
  • 49
  • +1 This should be the same as `FileWriter fw = new FileWriter(file, true);` as the FileWriter will just turn the `String` back into a `File`. – Peter Lawrey Feb 03 '14 at 20:56
1

Use this it will work

fw = new FileWriter("fileName",true);

for more details on FileWriter see this

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Girish
  • 1,717
  • 1
  • 18
  • 30