Skip to content

Java append to file with Apache Commons IO

Ramesh Fadatare edited this page Jul 12, 2019 · 1 revision

In this example, we use Apache Commons IO to append to a file.

We need below dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

Java append to file with Apache Commons IO

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;

public class JavaAppendFileApacheCommons {

    public static void main(String[] args) throws IOException {

        String fileName = "src/main/resources/sample.txt";

        File file = new File(fileName);

        FileUtils.writeStringToFile(file, "Append some data", StandardCharsets.UTF_8, true);
    }
}

We append to the file with the FileUtils.writeStringToFile() method. The last append parameter determines whether to append to a file.

Clone this wiki locally