Read And Write Text With Files.readString

Read and write whole text files in one call with Files.readString and writeString, choosing UTF-8 explicitly for predictable encoding.

JavaConfig Management

Code

snippet
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("read-string-");
        Path file = dir.resolve("notes.txt");

        // writeString 默认就是 UTF-8,这里显式写出便于审计
        Files.writeString(file, "alpha\nbeta\n", StandardCharsets.UTF_8);

        // readString 一次性读入整个文件,适合配置与小文本
        String text = Files.readString(file, StandardCharsets.UTF_8);
        System.out.println("lines: " + text.lines().count());
        System.out.println("ends with newline: " + text.endsWith("\n"));

        // 整文件覆盖:不是追加
        String updated = text.replace("beta", "gamma");
        Files.writeString(file, updated, StandardCharsets.UTF_8);
        System.out.println(Files.readString(file).strip());

        Files.deleteIfExists(file);
        Files.deleteIfExists(dir);
    }
}

How it works

Everything happens inside the class Main.

Using it

Output arrives with tags — lines:, ends with newline: — when the file runs.

Output is labeled for readability — expect lines prefixed with lines:, ends with newline:.

Key statements

Files.writeString(file, "alpha\nbeta\n", StandardCharsets.UTF_8);
String text = Files.readString(file, StandardCharsets.UTF_8);
Files.writeString(file, updated, StandardCharsets.UTF_8);

Interactive Tools for This Topic

FAQ

What does Read And Write Text With Files.readString print when run?
No setup needed: run the file and look for labeled lines like `lines:`, `ends with newline:` in the output.