This post will discuss how to append text at the end of a file in Java.

The text should be written at the end of the file rather than the beginning. If the file doesn’t exist, create a new one with the same name, and write data.

 
There are several ways to append text at the end of a file in plain Java and using third-party libraries such as Guava, Apache Commons IO, etc. All these are discussed below in detail:

1. Using Files.write() method

With the introduction of the Files class in Java 7, several static methods are included that operate on files, directories, or other types of files.

To write some text to a file, we can call Files.write(path, byte[], options) method. By default, the method creates a new file or overwrites an existing file. Since we need to append bytes to an existing file, pass the StandardOpenOption.APPEND option to it, as demonstrated below:

Download Code

 
The above code throws java.nio.file.NoSuchFileException if target file doesn’t exist. To create a new file when target file doesn’t exist, additionally pass the StandardOpenOption.CREATE option to Files.write() method, as shown below:

Download Code

2. Using FileWriter

We can even construct a FileWriter object for writing streams of characters into a file. FileWriter’s constructor takes the target file name with an optional boolean argument. The boolean argument, if true, indicates that bytes will be written at the end of the file rather than the beginning.

The following code directly calls the write() method, inherited from class java.io.Writer, to append a string in the file.

Download Code

3. Using Guava Library

Guava’s Files class has several utility methods for working with files. We can use its asCharSink() method with APPEND mode, which appends data at the end of the file without truncating it. When no mode is provided, the file will be truncated before writing, or a new file is created when the target file doesn’t exist.

Download Code

4. Using Apache Commons IO

We can also use the FileUtils class from Apache Commons IO library that has the writeStringToFile(File, String, Charset, mode) method, which writes a string to a file. If the last parameter to this method is true, then the String will be added to the file’s end rather than overwriting. Like Guava’s Files.asCharSink() method, it creates the file if it does not exist.

Download Code

That’s all about appending text to a file in Java.