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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.