Learn to append content to file in Java using BufferedWritter
, PrintWriter
, FileOutputStream
and Files
class. In all the examples, while opening the file to write, you have pass a second argument as true
which denotes that file is opened in append mode.
Table of Contents Append to File using Files class Append to File using BufferedWritter Append to File using PrintWriter Append to File using FileOutputStream
Append to File using Files class
With Files
class, we can write a file using it’s write()
function. Internally write()
function uses OutputStream
to write byte array into the file.
To append content to an existing file, Use StandardOpenOption.APPEND
while writing the content.
public static void usingPath() throws IOException { String textToAppend = "\r\n Happy Learning !!"; //new line in content Path path = Paths.get("c:/temp/samplefile.txt"); Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND); //Append mode }
Append to File using BufferedWritter
BufferedWritter
buffers before writing, so it result in less IO operations, so it improve the performance.
To append string to an existing file, open file writer in append mode with passing the second argument as true
.
public static void usingBufferedWritter() throws IOException { String textToAppend = "Happy Learning !!"; //Set true for append mode BufferedWriter writer = new BufferedWriter( new FileWriter("c:/temp/samplefile.txt", true)); writer.write(textToAppend); writer.close(); }
Append to File using PrintWriter
Use PrintWriter
to write formatted text to a file. This class implements all of the print methods found in PrintStream
, so you can use all formats which you use with System.out.println()
statements.
To append content to an existing file, open file writer in append mode by passing the second argument as true
.
public static void usingPrintWriter() throws IOException { String textToAppend = "Happy Learning !!"; FileWriter fileWriter = new FileWriter("c:/temp/samplefile.txt", true); //Set true for append mode PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println(textToAppend); //New line printWriter.close(); }
Append to File using FileOutputStream
Use FileOutputStream
to write binary data to a file. FileOutputStream
is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter
.
To append content to an existing file, open FileOutputStream
in append mode by passing second argument as true
.
public static void usingFileOutputStream() throws IOException { String textToAppend = "\r\n Happy Learning !!"; //new line in content FileOutputStream outputStream = new FileOutputStream("c:/temp/samplefile.txt", true); byte[] strToBytes = textToAppend.getBytes(); outputStream.write(strToBytes); outputStream.close(); }
Happy Learning !!
blue
Thank you