Java Files readString()

In this guide, you will learn about the Files readString() method in Java programming and how to use it with an example.

1. Files readString() Method Overview

Definition:

The readString() method belongs to the Files class in Java and is introduced in Java 11. This method is used to read all content from a file into a string, making it convenient to read file content with a single line of code.

Syntax:

1. Files.readString(Path path) throws IOException
2. Files.readString(Path path, Charset cs) throws IOException

Parameters:

- path: The Path object that locates the file to read.

- cs: Optional. The Charset to be used to decode the bytes to characters. If not provided, the UTF-8 charset is used by default.

Key Points:

- The method reads all the content of the file and returns it as a single String.

- The Charset for decoding can be optionally specified, default is UTF-8.

- Throws IOException if an I/O error occurs while reading from the file.

- Useful for reading small files, but care should be taken with large files to avoid OutOfMemoryError.

2. Files readString() Method Example

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

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

        try {
            String content = Files.readString(filePath);
            System.out.println("Content read from the file:");
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Content read from the file:
Java Files.writeString() Example

Explanation:

In this example, we specify a path to the file we want to read. We use the Files.readString() method to read the content of the file into a string. Then, we print the content to the console. If the file is not found or an I/O error occurs, the method will throw an IOException.

Comments