Java append to file with Apache Commons IO

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

Let's create a sample.txt file under "src/main/resources" folder and add some content to it. Now, below program will append "Append some data" string to "sample.txt" file.
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.


Comments