Java 文件处理的最佳实践:批量复制和移动文件
在 Java 项目中,文件处理是一个常见的需求,特别是在需要批量复制或移动文件时。本文将深入探讨如何使用 Java 处理文件,特别是利用 NIO(New Input/Output)包来简化文件操作。结尾附源文件!
文章目录
一、文件工具类的实现
下面是一个 FileUtil
工具类,提供了一系列文件处理功能,如获取文件扩展名、判断文件是否存在、输出文件、移动和复制目录等。
1. 移动文件或目录
public static void moveDirectoryContents(String sourceDirectory, String targetDirectory, List<String> whiteList) throws IOException {
Path sourcePath = Paths.get(sourceDirectory);
Path targetPath = Paths.get(targetDirectory);
// 确保源存在
if (!Files.exists(sourcePath)) {
throw new IOException("源路径不存在: " + sourceDirectory);
}
// 如果源是文件
if (Files.isRegularFile(sourcePath)) {
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
return;
}
// 处理目录移动逻辑
try {
Files.walk(sourcePath)
.filter(path -> !path.equals(sourcePath))
.filter(path -> whiteList.stream().noneMatch(item -> path.toString().conta