In this article, we will show how to append content to the existing file in Java. We are going to use BufferedWritter, PrintWriter, FileOutputStream and Files class available in Java IO. In Java appending methods are very similar to those responsible for writing the difference is in parameters.
2. Append to a file using BufferedWritter
BufferedWriter class can be used to append the content to an existing file. To append content add true parameter to the FileWriter constructor, like in the following example:
3. Append to a file using PrintWriter
Use PrintWriter to append formatted text to the file. PrintWriter comes with several methods to append any primitive types and objects. To activate append mode add second parameter to the FileWriter constructor.
4. Append to a file using FileOutputStream
FileOutputStream responsible for writing binary data to the file. In this case to turn on append mode we need to add true parameter to the constructor.
5. Append to a file using Files
To append content using Files class we must set third parameter for write method to StandardOpenOption.APPEND.
This article presented several methods to append content to the existing files in Java. Appending is very similar to writing to the file, the only difference is an additional parameter that tells we want to add content to the end of the file, not replacing it.
Like usual the following code snippets can be found in our GitHub repository.