今天拷贝了2万多张pdf到本地,需要把所有pdf放到同一个目录下方便后续操作,如果人工一个一个去处理的话,比较麻烦,所以写了一个程序来处理。
源文件目录结构如下:
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;
public class MovePdfFiles {
public static void main(String[] args) {
Path sourceDir = Paths.get("/history");
Path targetDir = Paths.get("/historynew");
// 创建目标目录
try {
Files.createDirectories(targetDir);
} catch (IOException e) {
System.err.println("无法创建目标目录: " + e.getMessage());
return;
}
// 遍历源目录树
try {
Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Files.isRegularFile(file) && file.toString().endsWith(".pdf")) {
// 移动文件
Files.move(file, targetDir.resolve(file.getFileName()), StandardCopyOption.REPLACE_EXISTING);
System.out.println("Moved file: " + file);
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
System.err.println("处理文件时出错: " + e.getMessage());
}
}
}