Maxim Gotovchits
Maxim Gotovchits

Reputation: 769

Opening and appending files

I need to open an existing file for appending and create new file for appending if it doesn't exist.

I tried PrintWriter function but it always create a new file and deletes the old. So could you help me? What should I use for that?

UPD: That's what I already tried

writer = new PrintWriter(System.getProperty("db.file"), "UTF-8");
writer.println("The first line");

Upvotes: 0

Views: 46

Answers (1)

ToYonos
ToYonos

Reputation: 16833

Try this

PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("your_file.txt", true)));

The true parameter of FileWriter indicates it has to append data.

To add specify encoding you can use

PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                     new FileOutputStream("your_file.txt", true), "UTF-8")));

Upvotes: 2

Related Questions