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.
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
:On line 2 change
new FileWriter(my_file_name)
tonew FileWriter(my_file_name, true)
so you're appending to the file rather than overwriting.you have to open the file in append mode, which can be achieved by using the
FileWriter(String fileName, boolean append)
constructor.should do the trick
You can use the
FileWriter(String fileName, boolean append)
constructor if you want to append data to file.Change your code to this:
From FileWriter javadoc:
Starting from Java 7:
Define a path and the String containing the line separator at the beginning:
and then you can use one of the following approaches:
Using
Files.write
(small files):Using
Files.newBufferedWriter
(text files):Using
Files.newOutputStream
(interoperable withjava.io
APIs):Using
Files.newByteChannel
(random access files):Using
FileChannel.open
(random access files):Details about these methods can be found in the Oracle's tutorial.
In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.