Path、Files 与 FileSystem API
Java 7 NIO.2 提供 Path 和 Files 类,替代传统 File 类进行文件操作。
Path 接口
创建 Path
Java
// 使用 Paths 工具类
Path path = Paths.get("file.txt");
Path path = Paths.get("/home", "user", "file.txt"); // 组合路径
Path path = Paths.get("C:\\Users\\file.txt"); // Windows
// 使用 Path.of(Java 11+)
Path path = Path.of("file.txt");
Path 常用方法
Java
Path path = Paths.get("/home/user/file.txt");
path.getFileName(); // file.txt(文件名)
path.getParent(); // /home/user(父目录)
path.getRoot(); // /(根路径)
path.getNameCount(); // 3(路径层级)
path.getName(0); // home(第 0 层)
path.subpath(0, 2); // home/user(子路径)
path.isAbsolute(); // true(是否绝对路径)
path.toAbsolutePath(); // 转为绝对路径
path.normalize(); // 去除冗余(/a/../b → /b)
path.resolve("sub.txt"); // 组合子路径
path.relativize(other); // 相对路径
Path vs File
Java
// File 转 Path
File file = new File("file.txt");
Path path = file.toPath();
// Path 转 File
Path path = Paths.get("file.txt");
File file = path.toFile();
Files 工具类
文件操作
Java
Path path = Paths.get("file.txt");
// 创建文件
Files.createFile(path);
// 创建目录
Files.createDirectory(Paths.get("dir"));
Files.createDirectories(Paths.get("dir/sub/sub")); // 创建多级目录
// 删除文件/目录
Files.delete(path); // 不存在抛异常
Files.deleteIfExists(path); // 不存在不抛异常
// 复制文件
Files.copy(src, dst);
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); // 覆盖
// 移动文件
Files.move(src, dst);
Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING);
读取文件
Java
Path path = Paths.get("file.txt");
// 读取全部内容(小文件)
List<String> lines = Files.readAllLines(path); // 按行读取
byte[] bytes = Files.readAllBytes(path); // 读取字节
String content = Files.readString(path); // Java 11+ 读取字符串
// 流式读取(大文件)
try (BufferedReader br = Files.newBufferedReader(path)) {
String line;
while ((line = br.readLine()) != null) {
// 处理每行
}
}
try (Stream<String> stream = Files.lines(path)) { // Java 8+ 流式读取
stream.forEach(System.out::println);
}
写入文件
Java
Path path = Paths.get("file.txt");
// 写入全部内容
Files.write(path, "Hello".getBytes());
Files.write(path, Arrays.asList("line1", "line2")); // 按行写入
Files.writeString(path, "Hello"); // Java 11+
// 流式写入
try (BufferedWriter bw = Files.newBufferedWriter(path)) {
bw.write("Hello");
}
// 追加写入
Files.write(path, "More".getBytes(), StandardOpenOption.APPEND);
文件属性
Java
Path path = Paths.get("file.txt");
Files.exists(path); // 是否存在
Files.notExists(path); // 是否不存在
Files.isDirectory(path); // 是否目录
Files.isRegularFile(path); // 是否普通文件
Files.isHidden(path); // 是否隐藏
Files.isReadable(path); // 是否可读
Files.isWritable(path); // 是否可写
Files.size(path); // 文件大小
// 获取文件属性
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
attrs.size();
attrs.creationTime();
attrs.lastModifiedTime();
attrs.isDirectory();
文件遍历
Java
// 遍历目录(深度优先)
Files.walk(Paths.get("dir"))
.forEach(System.out::println);
// 遍历目录(一层)
Files.list(Paths.get("dir"))
.forEach(System.out::println);
// 查找文件
Files.walk(Paths.get("dir"))
.filter(p -> p.toString().endsWith(".txt"))
.forEach(System.out::println);
FileSystem API
获取 FileSystem
Java
// 默认文件系统
FileSystem fs = FileSystems.getDefault();
// Path 分隔符
String separator = fs.getSeparator(); // Linux: /,Windows: \
// 根目录列表
Iterable<Path> roots = fs.getRootDirectories();
推荐使用 Path 和 Files:功能更丰富、API 更现代、异常处理更好,替代传统 File 类。
要点总结
- Path 表示文件路径,Paths.get() 创建
- Files 提供文件操作工具方法
- Files.readAllLines() 读取全部行,Files.lines() 流式读取
- Files.write() 写入,Files.copy() 复制,Files.move() 移动
- Files.walk() 遍历目录树,Files.list() 列出一层
- File 转 Path:file.toPath()
- 推荐 Path + Files 替代传统 File 类
📝 发现内容有误?点击此处直接编辑