Reading And Writing Files

The Files utility class handles common file operations with Path values. writeString and readString are concise choices for small text files.

File operations can fail for missing directories, permissions, storage errors, and many other environmental reasons, so they use checked IOException contracts.

Write, read, and remove

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

public class Main {
    public static void main(String[] args) throws Exception {
        Path log = Path.of("status.txt");
        Files.writeString(log, "build ready\n");
        String content = Files.readString(log);
        System.out.print(content.toUpperCase());
        System.out.println("Bytes: " + Files.size(log));
        Files.delete(log);
    }
}

Output:

BUILD READY
Bytes: 12

The program writes a short status, reads it back, and prints an uppercase version. Files.size reports the stored byte count before the temporary file is removed.

Do not load an unbounded large file with readString. Use buffered or streaming APIs when the data may not fit comfortably in memory.

Write one line to note.txt, then read the same file back as a String.