File 与 NIO
学习 File 操作、Path、Files 工具类、NIO Channel/Buffer
File 与 NIO
Java 7 引入的 NIO.2(java.nio.file)让文件操作更现代化。
学完本章你将: 掌握 Path、Files 工具类、NIO Channel/Buffer。
Path 取代 File
java
// 创建路径
Path path = Path.of("/home/user", "docs", "readme.txt");
Path cwd = Path.of(".").toAbsolutePath().normalize();
// 路径信息
System.out.println(path.getFileName()); // readme.txt
System.out.println(path.getParent()); // /home/user/docs
System.out.println(path.getRoot()); // /
// 路径操作
Path resolved = path.resolve("config.xml"); // 拼接
Path relative = cwd.relativize(path); // 相对路径
Files 工具类
java
// 读写文件
String content = Files.readString(Path.of("input.txt"));
Files.writeString(Path.of("output.txt"), "Hello NIO");
List<String> lines = Files.readAllLines(Path.of("data.csv"));
// 文件操作
Files.createDirectory(Path.of("newDir"));
Files.copy(Path.of("src.txt"), Path.of("dst.txt"),
StandardCopyOption.REPLACE_EXISTING);
Files.move(Path.of("old.txt"), Path.of("new.txt"));
Files.deleteIfExists(Path.of("temp.txt"));
// 遍历目录
try (Stream<Path> stream = Files.walk(Path.of("."))) {
stream.filter(Files::isRegularFile)
.forEach(System.out::println);
}
NIO Channel 与 Buffer
java
// FileChannel 高效文件复制
try (FileChannel src = FileChannel.open(Path.of("src.bin"));
FileChannel dst = FileChannel.open(Path.of("dst.bin"),
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
src.transferTo(0, src.size(), dst); // 零拷贝
}
// Buffer 读写
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("Hello".getBytes());
buffer.flip(); // 切换为读模式
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
对比
| 特性 | IO (java.io) | NIO (java.nio) |
|---|---|---|
| 流模型 | 阻塞 | 非阻塞 |
| 通道 | 单向 | 双向 |
| 缓冲 | 字节/字符 | Buffer 抽象 |
| 性能 | 一般 | 高(零拷贝) |