Java Files.write() Method Example

In this example, I show you how to write lines of text to a file in Java using Files.write() API.

java.nio.file.Files.write() API

This method is used to write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

Java Files.write() API Example

In the example, we write four text lines to a file located at "src/resources/sample.txt".
package net.javaguides.corejava.io;

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.ArrayList;
import java.util.List;

public class JavaWriteFile {

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

        Path myPath = Paths.get("src/resources/sample.txt");

        List < String > animals = new ArrayList < > ();
        // Adding new elements to the ArrayList
        animals.add("Lion");
        animals.add("Tiger");
        animals.add("Cat");
        animals.add("Dog");
        System.out.println(animals);

        Files.write(myPath, animals, StandardCharsets.UTF_8,
            StandardOpenOption.CREATE);

        System.out.println("Data written");
    }
}
Output:
Data written
Files.write() takes a file path, charset, and file open options as parameters. With StandardOpenOption.CREATE a file is created if it does not exist:
Files.write(myPath, lines, StandardCharsets.UTF_8, 
        StandardOpenOption.CREATE);

References

Comments