下面给你一份Java NIO 文件操作的常用写法总结,基于 java.nio.file 包(JDK 7+),比传统 IO 更简洁、效率更高。
Paths:创建 PathPath:文件路径Files:文件操作工具类FileSystem / FileChannel:底层通道(高级用法)import java.nio.file.*;
public class NioDemo {
public static void main(String[] args) throws Exception {
Path dir = Paths.get("testDir");
Path file = Paths.get("testDir/test.txt");
if (!Files.exists(dir)) {
Files.createDirectories(dir);
}
if (!Files.exists(file)) {
Files.createFile(file);
}
}
}
Path path = Paths.get("test.txt");
Files.write(path, "Hello NIO".getBytes());
Files.write(
path,
"append content".getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
byte[] data = Files.readAllBytes(path);
String content = new String(data);
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
try (Stream<String> stream = Files.lines(path)) {
stream.forEach(System.out::println);
}
Path src = Paths.get("a.txt");
Path dest = Paths.get("b.txt");
// 复制
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
// 移动
Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
// 删除
Files.deleteIfExists(dest);
Path root = Paths.get("testDir");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(root)) {
for (Path p : stream) {
System.out.println(p.getFileName());
}
}
Files.walk(root).forEach(System.out::println);
boolean isDir = Files.isDirectory(path);
long size = Files.size(path);
try (FileChannel in = FileChannel.open(src, StandardOpenOption.READ);
FileChannel out = FileChannel.open(dest,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE)) {
in.transferTo(0, in.size(), out);
}
✅ NIO 更适合:
⚠️ 小文件直接用 Files.readAllBytes 最简单
如果你有具体场景(比如:大文件读写、断点续传、 monitor 目录变化、网络 + NIO),我可以给你更针对性的代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。