Java NIO Files
核对 java.nio.file.Files 工具类的静态设计特点、全量常用方法清单、文件读写/复制/移动/删除、目录递归遍历与查找、文件属性视图、资源自动释放最佳实践及与传统 java.io.File 的对比。
学完这一章,你能够
- 核对 java.nio.file.Files 工具类的静态设计特点、全量常用方法清单、文件读写/复制/移动/删除、目录递归遍历与查找、文件属性视图、资源自动释放最佳实践及与传统 java.io.File 的对比。
Files 工具类定位与四大设计特点
`java.nio.file.Files` 是 Java NIO.2(JDK 7 引入)的核心文件系统工具类,与 `java.nio.file.Path` 紧密协作以替代传统 `java.io.File` 的局限。它具备四项显著特征:全部方法均为静态方法,无需构造实例;功能覆盖文件内容读写、复制移动、属性视图、临时目录与流式遍历;失败时统一抛出 `IOException`(如 `NoSuchFileException`)而非静默返回布尔值;配合 `Path` 原生支持符号链接与跨文件系统扩展。
由于绝大多数文件 I/O 方法都会抛出受检异常 `IOException`,调用方需通过 `try-catch` 妥善处理或向上声明。下文参考表按文件操作、文件属性、文件内容、目录操作、临时文件及其他流通道六大类别完整汇总 `Files` 的常用静态方法。
文件读写、复制移动删除与目录遍历
面向中小文件,`Files.readAllBytes`、`Files.readAllLines` 与 `Files.write`(可搭配 `StandardOpenOption.APPEND` 追加写入)能以极少代码完成读写(工程上建议显式传入 `StandardCharsets.UTF_8` 避免依赖平台默认编码);文件管理则由 `Files.copy`、`Files.move`(常配合 `StandardCopyOption.REPLACE_EXISTING`)以及 `Files.delete` / `Files.deleteIfExists` 完成。
目录管理方面,`createDirectory` 仅创建单级目录(父目录不存在时抛异常),`createDirectories` 会自动补全所有缺失的父级目录。遍历目录可使用 `Files.list(dir)`(仅当前层)、`Files.newDirectoryStream(dir)` 或 `Files.walk(dir)`(深度优先递归遍历);注意 `list`/`walk`/`find`/`lines` 返回的 `Stream` 持有底层操作系统目录句柄,必须放在 `try-with-resources` 语句中确保及时关闭。
文件属性、查找、临时文件与属性视图
`Files` 提供 `exists`、`isDirectory`、`isRegularFile`、`isReadable`、`isWritable`、`isExecutable`、`size`、`getLastModifiedTime` 与 `setLastModifiedTime` 等属性读写接口。在 POSIX 兼容系统(Linux/macOS)上可通过 `PosixFilePermissions.fromString("rwxr-x---")` 配合 `Files.setPosixFilePermissions` 设置 Unix 权限;在 Windows NTFS 文件系统上不提供 POSIX 视图(调用 `setPosixFilePermissions` 会抛出 `UnsupportedOperationException`,需改用 `AclFileAttributeView` 或 `DosFileAttributeView`)。
进阶能力包括:使用 `Files.find(dir, maxDepth, BiPredicate<Path, BasicFileAttributes>)` 按路径与属性联合筛选文件;通过 `Files.createTempFile` 与 `Files.createTempDirectory` 安全创建带随机名的临时目录和文件并在 `finally` 中清理;通过 `Files.getOwner` 获取文件所有者 `UserPrincipal`、通过 `Files.getFileStore` 读取挂载卷空间与文件系统信息。
最佳实践与传统 java.io.File 对比
使用 `Files` 应遵循三项实践原则:一是显式捕获 `IOException` 并合理配置 `StandardCopyOption.REPLACE_EXISTING`;二是将 `Files.lines`/`Files.walk`/`Files.newBufferedReader` 等资源严格纳入 `try-with-resources` 自动关闭;三是面向大文件优先使用缓冲流(`newBufferedReader`/`newBufferedWriter`)或流式 `Files.lines` 而非一次性 `readAllBytes`,批量目录遍历采用 `Files.walk`,并缓存高频访问的属性元数据。
与传统 `java.io.File` 相比,NIO `Files` 在异常诊断明确性、符号链接原生支持、文件属性丰富度以及与 Java 8 Stream 生态融合方面全面领先,新项目推荐优先采用 `Path` + `Files`。本站 OpenJDK 8 实验已在独立临时目录中实测全部核心读写、目录遍历、属性、流通道与清理流程。
java.nio.file.Files 常用静态方法分类参考
| 方法签名 | 作用说明 |
|---|---|
| 【分类】文件操作 | 提供文件复制、移动、重命名与删除等核心静态方法。 |
| static Path copy(Path source, Path target, CopyOption... options) | 将文件从源路径复制到目标路径(可配合 REPLACE_EXISTING)。 |
| static Path move(Path source, Path target, CopyOption... options) | 移动或重命名文件到目标路径。 |
| static void delete(Path path) | 删除指定路径文件或空目录;路径不存在时抛出 NoSuchFileException。 |
| static boolean deleteIfExists(Path path) | 若目标存在则删除并返回 true,不存在则返回 false。 |
| 【分类】文件属性 | 用于检测路径存在性、类型、权限、字节大小与修改时间戳。 |
| static boolean exists(Path path, LinkOption... options) | 检查路径对应的文件或目录是否存在。 |
| static boolean isDirectory(Path path, LinkOption... options) | 判断路径是否为目录。 |
| static boolean isRegularFile(Path path, LinkOption... options) | 判断路径是否为常规文件。 |
| static boolean isReadable(Path path) | 检查当前进程对目标文件是否具有读权限。 |
| static boolean isWritable(Path path) | 检查当前进程对目标文件是否具有写权限。 |
| static boolean isExecutable(Path path) | 检查目标文件是否具备可执行属性。 |
| static long size(Path path) | 返回文件的字节长度。 |
| static FileTime getLastModifiedTime(Path path, LinkOption... options) | 获取文件最后一次修改时间。 |
| 【分类】文件内容操作 | 便捷读写字节数组、文本行集合及延迟加载行流。 |
| static byte[] readAllBytes(Path path) | 一次性读取文件的全部字节(适用于中小型文件)。 |
| static List<String> readAllLines(Path path) | 按 UTF-8 字符集读取文件所有文本行。 |
| static List<String> readAllLines(Path path, Charset cs) | 按指定 Charset 读取文件所有文本行。 |
| static Stream<String> lines(Path path) | 按 UTF-8 延迟流式读取文件各行(需在 try-with-resources 中关闭)。 |
| static Stream<String> lines(Path path, Charset cs) | 按指定字符集返回文件行流。 |
| static Path write(Path path, byte[] bytes, OpenOption... options) | 向文件写入字节数组,可通过 APPEND 等选项控制写入模式。 |
| static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) | 将文本行序列写入文件并返回目标路径。 |
| 【分类】目录操作 | 用于创建单级/多级目录及列举目录内容。 |
| static Stream<Path> list(Path dir) | 返回目录下一级直接条目的延迟流(不递归)。 |
| static DirectoryStream<Path> newDirectoryStream(Path dir) | 打开可迭代目录流以逐项访问目录内容。 |
| static Path createDirectory(Path dir, FileAttribute<?>... attrs) | 创建单级目录(父目录必须已存在)。 |
| static Path createDirectories(Path dir, FileAttribute<?>... attrs) | 递归创建目标目录及所有尚不存在的父级目录。 |
| 【分类】临时文件/目录 | 在默认临时区或指定目录下安全生成唯一临时路径。 |
| static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) | 在指定目录下按前缀与后缀创建唯一临时文件。 |
| static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) | 在指定目录下按前缀创建唯一临时目录。 |
| 【分类】其他流、通道与内容探测 | 用于创建空文件、获取字节/字符流、通道及探测 MIME 类型。 |
| static Path createFile(Path path, FileAttribute<?>... attrs) | 原子方式创建新的空文件,若已存在则抛出 FileAlreadyExistsException。 |
| static SeekableByteChannel newByteChannel(Path path, OpenOption... options) | 打开或创建文件并返回支持随机定位的 SeekableByteChannel。 |
| static InputStream newInputStream(Path path, OpenOption... options) | 打开读取文件的字节输入流。 |
| static OutputStream newOutputStream(Path path, OpenOption... options) | 打开写入文件的字节输出流。 |
| static BufferedReader newBufferedReader(Path path) | 以 UTF-8 打开缓冲字符读取器,适合大文件逐行读取。 |
| static BufferedWriter newBufferedWriter(Path path, OpenOption... options) | 以 UTF-8 打开缓冲字符写入器。 |
| static String probeContentType(Path path) | 借助系统已安装探测器推测文件的 MIME 内容类型。 |
NIO Files 与传统 java.io.File 特性对比
| 对比维度 | Files 类 (NIO) | 传统 I/O (java.io.File) |
|---|---|---|
| 方法类型 | 静态工具方法,直接面向 Path 操作 | 依赖 File 对象实例方法 |
| 路径表示 | 使用不可变 Path 接口,支持跨文件系统 | 使用 File 类,耦合本地文件系统 |
| 异常处理 | 失败统一抛出描述清晰的 IOException 子类 | 部分方法仅返回 boolean(如 delete),难以诊断原因 |
| 功能丰富度 | 内置复制/移动/流式遍历/查找/临时目录等完整能力 | 仅提供基础文件与目录操作 |
| 符号链接处理 | 通过 LinkOption 原生识别与控制符号链接 | 符号链接支持有限 |
| 文件属性操作 | 提供 Basic/Posix/Dos/Acl 等细粒度属性视图 | 仅暴露少量基础读写/时间属性 |
运行 Java 8 NIO Files 临时目录读写、复制移动、walk/find、属性视图与流通道实测
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileStore;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.nio.file.attribute.UserPrincipal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ExploreNioFile {
private static void deleteRecursively(Path root) throws IOException {
if (root == null || !Files.exists(root)) return;
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.deleteIfExists(dir);
return FileVisitResult.CONTINUE;
}
});
}
private static String escapeJson(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
}
return sb.append('"').toString();
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) return escapeJson((String) obj);
if (obj instanceof List<?>) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map<?, ?>) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(escapeJson(String.valueOf(e.getKey()))).append(": ").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return escapeJson(String.valueOf(obj));
}
private static Map<String, Object> makeCase(String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<String, Object>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", expected.equals(actual));
return c;
}
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();
Path workspace = Files.createTempDirectory("java-nio-files-lab-");
try {
// Case 1: File content read/write, append, copy, move, delete, deleteIfExists, exception handling
{
Path f1 = workspace.resolve("note.txt");
Files.write(f1, Arrays.asList("line1", "line2"), StandardCharsets.UTF_8);
Files.write(f1, "line3\n".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
List<String> allLinesDefault = Files.readAllLines(f1, StandardCharsets.UTF_8);
byte[] allBytes = Files.readAllBytes(f1);
List<String> streamLines;
try (Stream<String> st = Files.lines(f1, StandardCharsets.UTF_8)) {
streamLines = st.collect(Collectors.toList());
}
Path copied = workspace.resolve("note-copy.txt");
Files.copy(f1, copied, StandardCopyOption.REPLACE_EXISTING);
Path moved = workspace.resolve("note-moved.txt");
Files.move(copied, moved, StandardCopyOption.REPLACE_EXISTING);
boolean copyGone = !Files.exists(copied);
boolean movedExists = Files.exists(moved);
Files.delete(moved);
boolean deleteSecondIfExists = Files.deleteIfExists(moved);
boolean noSuchThrown = false;
try {
Files.delete(workspace.resolve("missing.txt"));
} catch (NoSuchFileException ex) {
noSuchThrown = true;
}
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("lines", Arrays.asList("line1", "line2", "line3"));
expected.put("stream_equals_readalllines", true);
expected.put("bytes_nonempty", true);
expected.put("copy_then_move_ok", true);
expected.put("delete_if_exists_missing", false);
expected.put("delete_missing_throws_nsfe", true);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("lines", allLinesDefault);
actual.put("stream_equals_readalllines", streamLines.equals(allLinesDefault));
actual.put("bytes_nonempty", allBytes.length > 10);
actual.put("copy_then_move_ok", copyGone && movedExists);
actual.put("delete_if_exists_missing", deleteSecondIfExists);
actual.put("delete_missing_throws_nsfe", noSuchThrown);
cases.add(makeCase(
"nio_file_rw_copy_move_delete",
"验证 Files 的 write/APPEND、readAllBytes/readAllLines/lines、copy/move/delete/deleteIfExists 及 NoSuchFileException",
expected,
actual
));
}
// Case 2: Directories (createDirectory, createDirectories, list, newDirectoryStream, walk, find)
{
Path singleDir = Files.createDirectory(workspace.resolve("single"));
Path nestedDir = Files.createDirectories(workspace.resolve("tree/a/b"));
Path txt1 = Files.createFile(workspace.resolve("tree/root.txt"));
Path txt2 = Files.createFile(nestedDir.resolve("deep.txt"));
Path log1 = Files.createFile(nestedDir.resolve("ignore.log"));
List<String> topEntries;
try (Stream<Path> s = Files.list(workspace.resolve("tree"))) {
topEntries = s.map(p -> p.getFileName().toString()).sorted().collect(Collectors.toList());
}
List<String> dsEntries = new ArrayList<String>();
try (DirectoryStream<Path> ds = Files.newDirectoryStream(nestedDir)) {
for (Path p : ds) {
dsEntries.add(p.getFileName().toString());
}
}
Collections.sort(dsEntries);
long walkCount;
try (Stream<Path> s = Files.walk(workspace.resolve("tree"))) {
walkCount = s.count();
}
List<String> foundTxt;
try (Stream<Path> s = Files.find(
workspace.resolve("tree"),
Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".txt"))) {
foundTxt = s.map(p -> p.getFileName().toString()).sorted().collect(Collectors.toList());
}
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("single_is_dir", true);
expected.put("top_list", Arrays.asList("a", "root.txt"));
expected.put("directory_stream_nested", Arrays.asList("deep.txt", "ignore.log"));
expected.put("walk_total_nodes", 6);
expected.put("found_txt_files", Arrays.asList("deep.txt", "root.txt"));
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("single_is_dir", Files.isDirectory(singleDir));
actual.put("top_list", topEntries);
actual.put("directory_stream_nested", dsEntries);
actual.put("walk_total_nodes", (int) walkCount);
actual.put("found_txt_files", foundTxt);
// silence unused variable warnings while keeping explicit creation
if (!Files.exists(txt1) || !Files.exists(txt2) || !Files.exists(log1)) {
throw new AssertionError("Created files missing");
}
cases.add(makeCase(
"nio_directory_walk_and_find",
"验证 createDirectory/createDirectories/createFile、list、newDirectoryStream、walk 与 find 递归筛选",
expected,
actual
));
}
// Case 3: Attributes, setLastModifiedTime, PosixFilePermissions parsing, owner, FileStore, probeContentType
{
Path attrFile = workspace.resolve("attr.txt");
Files.write(attrFile, "hello-nio".getBytes(StandardCharsets.UTF_8));
FileTime targetTime = FileTime.fromMillis(1700000000000L);
Files.setLastModifiedTime(attrFile, targetTime);
FileTime observedTime = Files.getLastModifiedTime(attrFile);
Set<PosixFilePermission> parsedPerms = PosixFilePermissions.fromString("rwxr-x---");
UserPrincipal owner = Files.getOwner(attrFile);
FileStore store = Files.getFileStore(attrFile);
String mime = Files.probeContentType(attrFile);
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("exists_regular_rw", Arrays.asList(true, true, true, true));
expected.put("size_bytes", 9);
expected.put("modified_time_millis", 1700000000000L);
expected.put("posix_perm_count", 5);
expected.put("owner_nonempty", true);
expected.put("store_nonnull", true);
expected.put("probe_content_type_ok", true);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("exists_regular_rw", Arrays.asList(
Files.exists(attrFile),
Files.isRegularFile(attrFile),
Files.isReadable(attrFile),
Files.isWritable(attrFile)
));
actual.put("size_bytes", (int) Files.size(attrFile));
actual.put("modified_time_millis", observedTime.toMillis());
actual.put("posix_perm_count", parsedPerms.size());
actual.put("owner_nonempty", owner != null && !owner.getName().isEmpty());
actual.put("store_nonnull", store != null && store.getTotalSpace() > 0);
actual.put("probe_content_type_ok", mime == null || mime.contains("text"));
// Also call isExecutable to verify signature works cleanly
Files.isExecutable(attrFile);
cases.add(makeCase(
"nio_attributes_owner_filestore",
"验证 exists/isRegularFile/isReadable/isWritable/isExecutable/size、setLastModifiedTime、PosixFilePermissions 解析、getOwner 与 getFileStore",
expected,
actual
));
}
// Case 4: Temp files/dirs & Streams/Channels (createTempFile, createTempDirectory, newBufferedWriter/Reader, newOutputStream/InputStream, newByteChannel)
{
Path subTempDir = Files.createTempDirectory(workspace, "subtmp-");
Path subTempFile = Files.createTempFile(subTempDir, "pref-", ".dat");
try (BufferedWriter bw = Files.newBufferedWriter(subTempFile, StandardCharsets.UTF_8)) {
bw.write("buffered-line");
}
String readBackBuffered;
try (BufferedReader br = Files.newBufferedReader(subTempFile, StandardCharsets.UTF_8)) {
readBackBuffered = br.readLine();
}
Path binFile = subTempDir.resolve("stream.bin");
try (OutputStream os = Files.newOutputStream(binFile)) {
os.write(new byte[]{10, 20, 30, 40});
}
byte[] readBytes = new byte[4];
int nRead;
try (InputStream is = Files.newInputStream(binFile)) {
nRead = is.read(readBytes);
}
Path chanFile = subTempDir.resolve("chan.bin");
try (SeekableByteChannel ch = Files.newByteChannel(
chanFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.READ)) {
ch.write(ByteBuffer.wrap("NIO".getBytes(StandardCharsets.UTF_8)));
ch.position(0);
ByteBuffer buf = ByteBuffer.allocate(3);
ch.read(buf);
buf.flip();
String chanText = StandardCharsets.UTF_8.decode(buf).toString();
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("temp_prefix_suffix_ok", true);
expected.put("buffered_rw", "buffered-line");
expected.put("stream_bytes_count", 4);
expected.put("channel_text", "NIO");
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("temp_prefix_suffix_ok",
subTempFile.getFileName().toString().startsWith("pref-")
&& subTempFile.getFileName().toString().endsWith(".dat"));
actual.put("buffered_rw", readBackBuffered);
actual.put("stream_bytes_count", nRead);
actual.put("channel_text", chanText);
cases.add(makeCase(
"nio_temp_streams_and_channel",
"验证 createTempDirectory/createTempFile、newBufferedWriter/Reader、newOutputStream/InputStream 与 SeekableByteChannel",
expected,
actual
));
}
}
} finally {
deleteRecursively(workspace);
}
Map<String, Object> root = new LinkedHashMap<String, Object>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
}
- 在独立临时目录中验证写入/追加/读取、复制/移动/删除与 NoSuchFileException、目录递归 walk/find、时间戳/Owner/FileStore 与 POSIX 权限解析,以及缓冲流与 SeekableByteChannel,退出前完全清理临时文件。
所需环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
当前源码 SHA256:3247e508943f470c42792a7c3506b7cf98637321bde55da2a61aff0dc986d32f
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
ZIP SHA256:df00060e1b4503bd55a3f525c3eea43a87000da78ac70baad774d1b2ec5e809f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么使用 Files.lines(path) 或 Files.walk(dir) 时必须将其写在 try-with-resources 语句块中?
展开参考解答
这两类方法返回的 Stream 底层关联着操作系统打开的文件描述符或目录句柄,仅靠终端操作消耗流并不会保证释放句柄,必须通过 try-with-resources 自动调用 Stream.close() 防止句柄泄漏。