This article shows how to use the following Java APIs to append text to the end of a file.
- Files.write– Append a single line to a file, Java 7.
- Files.write– Append multiple lines to a file, Java 7, Java 8.
- Files.writeString– Java 11.
- FileWriter
- FileOutputStream
- FileUtils– Apache Commons IO.
In Java, for NIO APIs like Files.write, we can use StandardOpenOption.APPEND to enable the append mode. For examples:
// append a string to the end of the file
private static void appendToFile(Path path, String content)
        throws IOException {
        Files.write(path,
                        content.getBytes(StandardCharsets.UTF_8),
                        StandardOpenOption.CREATE,
                        StandardOpenOption.APPEND);
}
For classic IO APIs like FileWriter or FileOutputStream, we can pass a true to the constructor’s second argument to enable the append mode. For examples:
// append to the file
try (FileWriter fw = new FileWriter(file, true);
    BufferedWriter bw = new BufferedWriter(fw)) {
    bw.write(content);
    bw.newLine();
}
// append to the file
try (FileOutputStream fos = new FileOutputStream(file, true)) {
    fos.write(content.getBytes(StandardCharsets.UTF_8));
}
1. Append a single line to a file – Files.write
If the file does not exist, the API throws NoSuchFileException
Files.write(path, content.getBytes(StandardCharsets.UTF_8),
    StandardOpenOption.APPEND);The better solution always combines StandardOpenOption.CREATE and StandardOpenOption.APPEND. If the file does not exist, the API will create and write text to the file; if the file exists, append the text to the end of the file.
Files.write(path, content.getBytes(StandardCharsets.UTF_8),
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND);1.1 The below example shows how to append a single line to the end of a file.
FileAppend1.java
package com.favtuts.io.file;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileAppend1 {
    
    private static final String NEW_LINE = System.lineSeparator();
    public static void main(String[] args) throws IOException {            
        Path path = Paths.get("/home/tvt/workspace/favtuts/abc.txt");
        appendToFile(path, "hello world" + NEW_LINE);
    }
    // Java 7
    private static void appendToFile(Path path, String content) throws IOException {
        // if file not exists throws java.nio.file.NoSuchFileException
        /* Files.write(path, content.getBytes(StandardCharsets.UTF_8),
						StandardOpenOption.APPEND);*/
        // if file not exists, create and write to it
				// otherwise append to the end of the file
        
        Files.write(path, content.getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.CREATE,
            StandardOpenOption.APPEND
        );
    }
}
Output
Run 1st time.
abc.txt
hello worldRun 2nd time.
hello world
hello world2. Append multiple lines to a file – Files.write
The Files.write also supports the Iterable interface for multiple lines, we can append a List into a file.
FileAppend2.java
package com.favtuts.io.file;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
public class FileAppend2 {
    
    private static final String NEW_LINE = System.lineSeparator();
    public static void main(String[] args) throws IOException {            
        Path path = Paths.get("/home/tvt/workspace/favtuts/abc.txt"); 
        List<String> list = Arrays.asList("hello", "world", "favtuts");
        appendToFileJava8(path, list);
    }
    // apend lines of text
    private static void appendToFileJava8(Path path, List<String> list) throws IOException {
        // Java 7?
        /*Files.write(path, list, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);*/
        
        // Java 8, default utf_8
        Files.write(path, list,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    }
}
3. Java 11 – Files.writeString in append mode.
In Java 7, we need to convert a String into a byte[] and write or append it to a file.
String content = "...";
Files.write(path, content.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);In Java 11, we can use the new Files.writeString API to write or append a string directly into a file. The append mode works the same way.
FileAppend3.java
package com.favtuts.io.file;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
public class FileAppend {
    private static final String NEW_LINE = System.lineSeparator();
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/home/tvt/workspace/favtuts/abc.txt");
        String content = "hello world" + NEW_LINE;
 
        appendToFileJava11(path, content);
    }
    // Java 11, writeString, append mode
    private static void appendToFileJava11(Path path, String content) throws IOException {
        // utf_8
        /*
         * Files.writeString(path, content, StandardCharsets.UTF_8,
         * StandardOpenOption.CREATE,
         * StandardOpenOption.APPEND);
         */
        // default StandardCharsets.UTF_8
        Files.writeString(path, content,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
    }
}
4. FileWriter
For the legacy IO APIs like FileWriter, the constructor’s second argument indicates the append mode.
// append
// if file not exists, create and write
// if the file exists, append to the end of the file
try (FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw)) {
        bw.write(content);
        bw.newLine();   // add new line, System.lineSeparator()
}4.1 The below example shows how to use FileWriter to append a single line to the end of a file.
FileAppend4_1.java
package com.favtuts.io.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileAppend4 {
    private static final String NEW_LINE = System.lineSeparator();
    public static void main(String[] args) throws IOException {
        
        File file = new File("/home/tvt/workspace/favtuts/abc.txt");
        String content = "hello world" + NEW_LINE;
        appendToFileFileWriter(file, content);
    }
    private static void appendToFileFileWriter(File file, String content)
            throws IOException {
        // default - create and write
        // if file not exists, create and write
        // if file exists, truncate and write
        /*
         * try (FileWriter fw = new FileWriter(file);
         * BufferedWriter bw = new BufferedWriter(fw)) {
         * bw.write(content);
         * bw.newLine();
         * }
         */
        // append mode
        // if file not exists, create and write
        // if file exists, append to the end of the file
        try (FileWriter fw = new FileWriter(file, true);
                BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(content);
            bw.newLine(); // add new line, System.lineSeparator()
        }
    }
}
4.2 The below example append a List or multiple lines to the end of a file.
FileAppend4_2.java
package com.favtuts.io.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FileAppend4 {
    private static final String NEW_LINE = System.lineSeparator();
    public static void main(String[] args) throws IOException {
        File file = new File("/home/tvt/workspace/favtuts/abc.txt");
        List<String> lines = Arrays.asList("hello", "world", "favtuts");
        appendToFileFileWriter(file, lines);
    }
    private static void appendToFileFileWriter(
            File file, List<String> lines) throws IOException {
        try (FileWriter fw = new FileWriter(file, true);
                BufferedWriter bw = new BufferedWriter(fw)) {
            for (String s : lines) {
                bw.write(s);
                bw.newLine();
            }
        }
    }
}
5. FileOutputStream
The append mode of FileOutputStream is working the same as FileWriter.
    private static void appendToFileFileOutputStream(File file, String content)
            throws IOException {
        // append mode
        try (FileOutputStream fos = new FileOutputStream(file, true)) {
            fos.write(content.getBytes(StandardCharsets.UTF_8));
        }
    }
6. FileUtils
The below example uses the popular Apache commons-io FileUtils.writeStringToFile to append a string to the end of a file.
pom.xml
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>
import org.apache.commons.io.FileUtils;
    private static void appendToFileFileUtils(File file, String content)
            throws IOException {
        // append mode
        FileUtils.writeStringToFile(
                file, content, StandardCharsets.UTF_8, true);
    }
Review the FileUtils.writeStringToFile signature; the last or fourth argument indicates the append mode.
public static void writeStringToFile(final File file, final String data,
            final Charset charset,final boolean append)
            throws IOException {
    try (OutputStream out = openOutputStream(file, append)) {
        IOUtils.write(data, out, charset);
    }
}
7. In the old days.
Before Java 7, we can use the FileWriter to append text to a file and close the resources manually.
    private static void appendToFileClassic(String fileName, String content) throws IOException {
        BufferedWriter bw = null;
        FileWriter fw = null;
        try {
            fw = new FileWriter(fileName, true);
            bw = new BufferedWriter(fw);
            bw.write(content);
        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (fw != null)
                    fw.close();
            } catch (IOException ex) {
                System.err.format("IOException: %s%n", ex);
            }
        }
    }
P.S. The above code is just for fun and legacy purposes, always sticks with try-with-resources to close resources.
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-io/file