How do I read a text file using Files.readString() in Java?

You can use Files.readString() to read an entire text file into a single string. It preserves the file’s line separators, so the result can contain multiple lines.

In this example, you will read a UTF-8 text file and display its contents.

Source code

Save the following code as ReadStringExample.java:

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

public class ReadStringExample {
    void main() {
        Path path = Path.of("message.txt");

        try {
            String content = Files.readString(path, StandardCharsets.UTF_8);

            IO.print(content);
        } catch (IOException exception) {
            System.err.println("Could not read the file: " + exception.getMessage());
        }
    }
}

Prepare the text file

Create a file named message.txt in the directory from which you will run the program. Save it using UTF-8 encoding with the following contents:

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

Explanation

The example creates a Path representing the file location:

Path path = Path.of("message.txt");

This is a relative path. Java resolves it against the program’s current working directory, which may differ from the directory containing the source file.

Reading the contents

The following statement reads the entire file:

String content = Files.readString(path, StandardCharsets.UTF_8);

The first argument identifies the file. The second specifies how its bytes are decoded into characters.

Using StandardCharsets.UTF_8 makes the expected encoding explicit. The overload Files.readString(path) also uses UTF-8.

The method returns one string containing all the text, including any line separators in the file.

Displaying the text

The program prints the contents using:

IO.print(content);

IO.print() does not append a line separator. This lets the program display the text without adding an extra newline beyond those already in the file.

Handling read failures

Files.readString() can throw an IOException, for example when the file is missing or cannot be read.

The catch block handles that failure:

catch (IOException exception) {
    System.err.println("Could not read the file: " + exception.getMessage());
}

The error message goes to standard error, while the file contents go to standard output.

You do not need to close a reader yourself. Files.readString() manages the file resource and closes it when reading finishes or an error occurs.

Run the example

With message.txt in your current directory, compile and run the program:

javac ReadStringExample.java
java ReadStringExample

Output

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

Use Files.readString() for files that comfortably fit in memory. For large files, process the contents incrementally with a buffered reader or Files.lines() instead.

How do I read and write files with Files.readString() and Files.writeString()?

In Java, Files.readString and Files.writeString (introduced in Java 11) are the most straightforward ways to handle small-to-medium-sized text files. They handle the opening, closing, and encoding for you in a single line of code.

Here is how you can use them:

1. Reading a File to a String

Files.readString(Path) reads the entire content of a file into a String. By default, it uses UTF-8 encoding.

package org.kodejava.nio;

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

public class ReadExample {
    public static void main(String[] args) {
        Path filePath = Path.of("example.txt");

        try {
            // Reads the whole file into a String using UTF-8
            String content = Files.readString(filePath);
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Writing a String to a File

Files.writeString(Path, CharSequence) writes text to a file. If the file doesn’t exist, it creates it. If it does exist, it overwrites it by default.

package org.kodejava.nio;

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

public class WriteExample {
    public static void main(String[] args) {
        Path filePath = Path.of("example.txt");
        String data = "Hello, Java developers!\nThis is a test.";

        try {
            // Overwrites the file with the string content
            Files.writeString(filePath, data);

            // To APPEND instead of overwrite, use StandardOpenOption:
            // Files.writeString(filePath, "\nMore data", StandardOpenOption.APPEND);

            System.out.println("File written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Key Points to Remember:

  • Memory Usage: Both methods load the entire file content into memory. Do not use them for very large files (e.g., gigabyte-sized logs), as they could cause an OutOfMemoryError.
  • Encoding: Both methods use UTF-8 by default. If you need a different encoding, you can pass a Charset as an additional argument:
    Files.readString(path, StandardCharsets.ISO_8859_1);
  • Exceptions: Both methods throw IOException, so they must be used within a try-catch block or a method that declares throws IOException.
  • Path API: Use Path.of("path/to/file") (Java 11+) or Paths.get("path/to/file") to create the Path object needed for these methods.