CompilingCyborg CompilingCyborg - 1 year ago 157
Java Question

How to add a new line of text to an existing file in Java?

I would like to append a new line to an existing file without erasing the current information of that file. In short, here is the methodology that I am using the current time:


Writer output;
output = new BufferedWriter(new FileWriter(my_file_name)); //clears file every time
output.append("New Line!");

The problem with the above lines is simply they are erasing all the contents of my existing file then adding the new line text.

I want to append some text at the end of the contents of a file without erasing or replacing anything.

Answer Source

you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.

output = new BufferedWriter(new FileWriter(my_file_name, true));

should do the trick

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download