Apache FileUtils writing to file

This example demonstrates how to write a string and a list of strings to file using the Apache commons library.

Maven Dependency

Let's add maven dependency before creating these examples:


Apache FileUtils writing file

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

public class WriteFileEx {

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

        String string = "Today is a gloomy day.";
        File myfile = new File("src/main/resources/myfile.txt");
        FileUtils.writeStringToFile(myfile, string, 
        List lines = new ArrayList<>();
        lines.add("A dark forest.");
        lines.add("A stray dog.");
        lines.add("A massive mountain.");
        File myfile2 = new File("src/main/resources/myfile2.txt");
                StandardCharsets.UTF_8.name(), lines);

A string is written to a file with FileUtils.writeStringToFile() and a collection of strings with FileUtils.writeLines().