Java Files.readString() and Files.writeString() Example

1. Introduction

This blog post covers Files.readString() and Files.writeString(), two convenient methods introduced in Java 11. These methods simplify the process of reading from and writing to files, making file handling in Java more straightforward and efficient.

Definition

- Files.readString(Path) is a method for reading all content from a file into a String, reducing the need for manual buffering and reading.

- Files.writeString(Path, CharSequence, OpenOption...) writes a CharSequence to a file, creating the file if it does not exist or overwriting its content.

2. Program Steps

1. Write a string to a file using Files.writeString().

2. Read the content of the file back into a string using Files.readString().

3. Display the read content.

3. Code Program

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

public class ReadWriteStringExample {
    public static void main(String[] args) {
        Path filePath = Path.of("example.txt");
        String contentToWrite = "Hello, Java 11!";

        try {
            // Writing content to the file
            Files.writeString(filePath, contentToWrite);

            // Reading content from the file
            String readContent = Files.readString(filePath);

            // Displaying the content read from the file
            System.out.println("Content read from file: " + readContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Content read from file: Hello, Java 11!

Explanation:

1. filePath is a Path object representing the file example.txt.

2. Files.writeString() writes the string Hello, Java 11! to example.txt. The file is created if it does not exist.

3. Files.readString() reads the content of example.txt back into a string.

4. The content read from the file is then printed to the console, demonstrating that the write and read operations were successful.

5. This example illustrates the simplicity and effectiveness of Files.readString() and Files.writeString() for basic file I/O operations in Java.


Comments