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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.