00:00

Files.readString() and Files.writeString() in Java 11

Last updated: · Standard (Java 11)

Java 11 added Files.readString(Path) and Files.writeString(Path, CharSequence, OpenOption...) to java.nio.file.Files. They read or write a whole text file in a single call and use UTF-8 unless you pass another charset.

This tutorial shows both methods, how to append, how they compare with older code, and when not to use them.

1. Why Were These Methods Added?

Reading a small text file used to need a BufferedReader loop, or new String(Files.readAllBytes(path), charset). Both are easy to get wrong, especially the charset. The new methods make the common case one readable line with a sensible default.

2. Method Signatures

Signatures.java
static String readString(Path path) throws IOException                       // UTF-8
static String readString(Path path, Charset cs) throws IOException

static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOException
static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException

Without options, writeString creates the file or truncates an existing one, like CREATE, TRUNCATE_EXISTING and WRITE.

3. Practical Examples

Example 1: Write, append and read

ReadWriteString.java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class ReadWriteString {
    public static void main(String[] args) throws IOException {
        Path notes = Files.createTempFile("notes", ".txt");

        // writeString: one call, UTF-8 by default, returns the path
        Files.writeString(notes, "Buy milk\n");
        // Options work as with Files.write, e.g. APPEND
        Files.writeString(notes, "Pay rent\n", StandardOpenOption.APPEND);

        // readString: the whole file as one String (UTF-8 by default)
        String content = Files.readString(notes);
        System.out.print(content);
        System.out.println("Characters: " + content.length());

        // A charset can be passed explicitly
        Files.writeString(notes, "Café ₹50", StandardCharsets.UTF_8);
        System.out.println("Read back : " + Files.readString(notes, StandardCharsets.UTF_8));
        System.out.println("Bytes     : " + Files.size(notes));

        Files.delete(notes);
    }
}
Output
Buy milk
Pay rent
Characters: 18
Read back : Café ₹50
Bytes     : 11

The text Café ₹50 has 8 characters but 11 bytes in UTF-8, because é needs 2 bytes and ₹ needs 3.

Example 2: Old and new code side by side

BeforeAndAfter.java
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class BeforeAndAfter {
    // Before Java 11: read all bytes and decode, or loop with a reader
    static String readOld(Path file) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) throws IOException {
        Path config = Files.createTempFile("app", ".properties");
        Files.writeString(config, "port=8080\nmode=dev\n");

        String before = readOld(config);
        String after = Files.readString(config);       // Java 11: one line
        System.out.println("Same content: " + before.equals(after));

        // Combine with String.lines() from Java 11
        after.lines()
             .filter(l -> l.startsWith("port"))
             .forEach(l -> System.out.println("Found " + l));

        try {
            Files.readString(config.resolveSibling("missing.properties"));
        } catch (IOException e) {
            System.out.println("Missing file: " + e.getClass().getSimpleName());
        }
        Files.delete(config);
    }
}
Output
Same content: true
Found port=8080
Missing file: NoSuchFileException

4. How readString Works

Files.readString decoding steps readString opens the file, reads all bytes, decodes them with UTF-8 or the given charset, and returns a String. Malformed input causes an exception instead of silent replacement. Path notes.txt read all bytes whole file in memory decode UTF-8 by default String returned to caller
Figure 1: The whole file is read into memory, so these methods suit small and medium files.

5. Important Points and Best Practices

  • Use them for small files such as configuration, templates and test data; for large files use Files.lines or a BufferedReader.
  • readString throws MalformedInputException if the bytes are not valid in the charset, instead of replacing them silently.
  • Pass StandardOpenOption.APPEND to add to a file and CREATE_NEW to fail if it already exists.
  • Missing files cause NoSuchFileException, a subclass of IOException.

6. Summary

  • Java 11 added Files.readString and Files.writeString.
  • Both use UTF-8 by default and accept an explicit Charset.
  • writeString accepts open options such as APPEND.
  • They load the whole file into memory, so use streaming APIs for big files.

Related Tutorials

7. References