I/O 与 NIO
i-o-operations、file-operations。
30 分钟
I/O 与 NIO
读写配置文件、日志与课时 Markdown 离不开 I/O。java-fundamentals 可能已碰过 File——本课系统讲 字节流/字符流、try-with-resources 与 NIO Path/Files。
学习目标
- 区分 InputStream/OutputStream 与 Reader/Writer
- 用 try-with-resources 自动关闭资源
- 使用
java.nio.file读写文本与遍历目录
经典 IO:流
// 读文本:字符流 + 缓冲
try (BufferedReader reader = Files.newBufferedReader(
Path.of("content/lesson.md"), StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
// 写文本
try (BufferedWriter writer = Files.newBufferedWriter(
Path.of("out/summary.txt"), StandardCharsets.UTF_8)) {
writer.write("jvc-io done");
}
| 类型 | 单位 | 典型类 |
|---|---|---|
| 字节流 | byte | InputStream / OutputStream |
| 字符流 | char(处理编码) | Reader / Writer |
| 缓冲 | 减少系统调用 | BufferedReader / BufferedWriter |
文本用字符流并指定 Charset;二进制(图片、序列化)用字节流。
try-with-resources
try (InputStream in = new FileInputStream("data.bin")) {
in.readAllBytes();
} // 自动 close,即使抛异常
实现 AutoCloseable 的资源都可放在 try 头;多个资源用分号分隔。避免手动 finally 里 close 漏写。
NIO Path 与 Files
Path root = Path.of("content/课程/java-core-essentials/drafts");
Files.list(root)
.filter(p -> p.toString().endsWith(".md"))
.forEach(System.out::println);
String content = Files.readString(root.resolve("jvc-io.md"));
Files.writeString(Path.of("out/copy.md"), content);
Path替代File,API 更一致Files.readString/writeString(JDK 11+)适合中小文件- 大文件用
Files.newInputStream+ 缓冲分块读
与构建/测试的关系
Gradle/Maven 把 src/main/resources 打进 classpath(见 );测试里常用 写临时文件(见 )。