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.
append("New Line!"); output.
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.
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.
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
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With