This example will show how to append text to a file using java, java 7 NIO, guava Files and apache commons. Each snippet will append text to an output file called AppendTextToFile.txt as described in the set up section below.
Setup
Straight up Java
Using a technique prior to Java 7, this snippet will create a file instance by passing a pathname as a string. Next we will construct a FileWriter object by passing in the File object and passing in true as a second argument. The second argument tells the FileWriter to append the bytes to the end of the file rather than the beginning.
Output
The text file “AppendTextToFile.txt” now contains
Java 7 File I/O
In this snippet we will show how to append text to the end of a file using Java 7 file nio. By using the automatic resource management introduced in java 7 which eliminates the verbose code blocks and simplified working with connections, files or streams we will create a new PrintWriter from a BufferedWritter. Then we will write to the file by calling PrintWriter.out and passing it text.
Output
The text file “AppendTextToFile.txt” now contains
Google Guava
Guava Files class provides utility methods for working with files. We will use this class to calling the append passing it a file and passing it the charset used to encode the output stream. The Charset constant class used is contained in guava which you could substitute with the Charset class introduced in java 7.
Output
The text file “AppendTextToFile.txt” now contains
Apache Commons
Apache commons FileUtils provides similar functionality that will write a string to end of the file.
Output
The text file “AppendTextToFile.txt” now contains