Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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

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.

like image 220
CompilingCyborg Avatar asked Jan 06 '11 11:01

CompilingCyborg


People also ask

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

append("New Line!"); output.

How do you append to an existing file in Java?

You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using a special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode.

How do I add multiple lines to a text file in Java?

boolean append = true; String filename = "/path/to/file"; BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append)); // OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer. write(line1); writer. newLine(); writer.


2 Answers

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

like image 134
Mario F Avatar answered Sep 28 '22 05:09

Mario F


The solution with FileWriter is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!

So at best use FileOutputStream:

    Writer writer = new BufferedWriter(new OutputStreamWriter(         new FileOutputStream(file, true), "UTF-8")); 
like image 30
Danubian Sailor Avatar answered Sep 28 '22 03:09

Danubian Sailor