实现说明
Files.readString 读写文本以类 Main为骨架。
使用要点
- 跑完文件,输出里会留下标记——
lines:、ends with newline:。
常见问题
运行「Files.readString 读写文本」会打印什么?
运行文件本身,lines:、ends with newline: 这些前缀各对应一段演示逻辑。
核心语句
Files.writeString(file, "alpha\nbeta\n", StandardCharsets.UTF_8);
String text = Files.readString(file, StandardCharsets.UTF_8);
Files.writeString(file, updated, StandardCharsets.UTF_8);
代码示例
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);
}
}