How to Append to a File in Java

In the post How to Write to a File in Java examples are already given to write to a file in Java but the examples shown there would create a new file or overwrite existing file when writing. Sometimes you may need to append to an existing file rather than overwriting it so this post shows options to append content to a file in Java.

In Java there are two classes FileWriter and FileOutputStream for writing to a file. Where FileWriter is meant for writing streams of characters and FileOutputStream is used for writing streams of raw bytes. Both of these classes have a constructor with a boolean argument. When that boolean argument is passed as true then the content will be written to the end of the file.

As example – public FileWriter(File file, boolean append);

You should always used the wrapper classes BufferedWriter and BufferedOutputStream rather than using these classes directly.

Apart from these classes Files class added in Java 7 also provides methods for appending to a file in Java. There is Files.write() method which can be used.

Another method is-

Java program to append to a file in Java

Let’s see examples of appending to a file in Java using the above mentioned options.

Appending to a file using Java BufferedWriter

Appending to a file using Java BufferedOutputStream

If you have to write raw bytes then you can use BufferedOutputStream class. In the example code getBytes() method is used to encode string into bytes.

Java program to append to a file using Files.write() method

Append to a file using Files.newBufferedWriter() method

Here try-with-resources is used to close the resources automatically rather than closing them explicitly using finally block.

That’s all for the topic How to Append to a File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.