Arc
Arc

Reputation: 449

File Writer overrides previous write Java

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?

Upvotes: 1

Views: 2195

Answers (2)

Lalit Chattar
Lalit Chattar

Reputation: 1984

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

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

Upvotes: 3

Girish
Girish

Reputation: 1717

Use this it will work

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

for more details on FileWriter see this

Upvotes: 1

Related Questions