How do I write text to a file using Files.writeString() in Java?

Use Files.writeString() to save a string to a text file. By default, it uses UTF-8, creates the file if it does not exist, and replaces its contents if it already exists.

In this example, you will write a two-line message to a file named greeting.txt.

Source code

Save the following code as WriteStringExample.java:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteStringExample {
    void main() {
        Path path = Path.of("greeting.txt");

        String message = """
                Hello, Java!
                Learning Java one snippet at a time.
                """;

        try {
            Files.writeString(path, message);
            IO.println("Text written to " + path);
        } catch (IOException exception) {
            System.err.println(
                    "Could not write the file: " + exception.getMessage());
        }
    }
}

Explanation

Path.of("greeting.txt") creates a relative path. The program writes the file in its current working directory, which is normally the directory from which you run the java command.

The triple quotes (""") define a text block. This lets you write multiple lines without adding \n between them. Because the closing quotes are on their own line, the string also ends with a newline.

The following statement saves the message:

Files.writeString(path, message);

Files.writeString() encodes the string as UTF-8 and writes it as supplied. It does not add a newline of its own. The method handles opening and closing the file, so there is no writer to close in your code.

The catch block handles an IOException, which can occur if the directory is not writable. The success message appears only if the write completes without throwing an exception.

Run the example

Compile and run the file from a directory where you can create greeting.txt:

javac WriteStringExample.java
java WriteStringExample

The program prints:

Text written to greeting.txt

Open greeting.txt to see its contents:

Hello, Java!
Learning Java one snippet at a time.

Appending instead of replacing

To keep existing contents and add the message at the end, import java.nio.file.StandardOpenOption and replace the write statement with:

Files.writeString(
        path, message,
        StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);

CREATE creates the file if it is missing, and APPEND writes at the end if it already exists. If the existing text does not end with a newline, the appended text starts on the same line.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.