Course contentsShow
← Java
Lesson 2037 of 2,87041. NIO.2 and the Path APIFree lesson

Reading as a String: Files.readString (Java 11+)

Discover the convenient Files.readString method for reading an entire file into a single String.

Reading as a String: Files.readString (Java 11+)

What you'll learn: How to use Files.readString() to load an entire text file into a single String in one convenient method call.

The Simplest Way to Read Text Files

If you've been using Files.readAllBytes() to get raw bytes or Files.readAllLines() to get a list of lines, Java 11 introduced an even more convenient method for text files: Files.readString(). This method reads the entire file content and returns it as a single String, handling character encoding automatically.

Think of it like ordering a pizza: readAllBytes() gives you raw ingredients, readAllLines() gives you pre-sliced pieces, and readString() hands you the complete pizza ready to eat — exactly what you ordered in one piece.

How It Works

The Files.readString() method reads the entire file content, decodes the bytes using the specified (or default) charset, and returns a single String with all line separators preserved:

import java.nio.file.*;
import java.io.IOException;

public class ReadStringExample {
    public static void main(String[] args) {
        Path configPath = Paths.get("config.txt");
        
        try {
            String content = Files.readString(configPath);
            System.out.println("File content:");
            System.out.println(content);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

You can also specify the charset explicitly:

import java.nio.charset.StandardCharsets;

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

When to Use readString

This method is perfect for configuration files, templates, or small-to-medium text files where you want to process the entire content as one string. It preserves all line breaks and formatting, unlike readAllLines() which splits and removes line terminators.

Key Takeaway: Files.readString() provides the most straightforward way to read an entire text file into a single String object, combining simplicity with proper character encoding support (Java 11+).