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:

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.nio.charset.StandardCharsets;

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.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course