Append text to file

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

private String OUTPUT_FILE_NAME = "AppendTextToFile.txt";

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.

@Test
public void append_to_file_java () throws IOException {
    
    File file = new File(OUTPUT_FILE_NAME);
    
    FileWriter fileWriter = new FileWriter(file, true);
    fileWriter.append("Append text to file w/ java");
    fileWriter.close();
}

Output

The text file “AppendTextToFile.txt” now contains

Append text to file w/ java

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.

@Test
public void append_to_file_java_7 () {
    
    try(PrintWriter out = new PrintWriter(
            new BufferedWriter(
                    new FileWriter(OUTPUT_FILE_NAME, true)
                    )
            )) {
        
        out.println("Append to file w/ Java 7");
    } catch (IOException e) {
        logger.error(e);
    }
}

Output

The text file “AppendTextToFile.txt” now contains

Append to file w/ Java 7

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.

@Test
public void append_to_file_guava () throws IOException {
    
    File file = new File(OUTPUT_FILE_NAME);

    Files.append("Append text to file w/ guava", 
            file, 
            Charsets.UTF_8);
}

Output

The text file “AppendTextToFile.txt” now contains

Append text to file w/ guava

Apache Commons

Apache commons FileUtils provides similar functionality that will write a string to end of the file.

@Test
public void append_to_file_apache () throws IOException {

    File file = new File(OUTPUT_FILE_NAME);
    
    FileUtils.writeStringToFile(
            file, 
            "Append text to file w/ apache", 
            true);
    
}

Output

The text file “AppendTextToFile.txt” now contains

Append text to file w/ apache