通过传递参数的方法移动原文件夹的文件,没有目标文件夹则创建,如果源文件夹不存在或者不是一个文件夹,会抛出相应的异常;同样地,如果目标文件夹已经存在但不是一个文件夹,也会抛出异常。
public static void main(String[] args) throws IOException {
String downloadFolderPath = "/storage/emulated/0/Download"; // Download 文件夹路径
String targetFolderPath = "/storage/emulated/0/TargetFolder"; // 目标文件夹路径
moveFilesFromDownloadToAnotherFolder(downloadFolderPath, targetFolderPath);
}
//移动文件夹中的文件
//sourceFolderPath 原文件夹 destinationFolderPath 目标文件夹
private static void moveFilesFromDownloadToAnotherFolder(String sourceFolderPath, String destinationFolderPath) throws IOException {
File sourceFolder = new File(sourceFolderPath);
if (!sourceFolder.exists() || !sourceFolder.isDirectory()) {
throw new IllegalArgumentException("源文件夹或文件不存在或不是一个目录");
}
File destinationFolder = new File(destinationFolderPath);
if (!destinationFolder.exists()) {
boolean created = destinationFolder.mkdirs();
if (!created) {
throw new IOException("创建目标文件夹失败");
}
} else if (!destinationFolder.isDirectory()) {
throw new IllegalArgumentException("目标路径存在但不是文件夹");
}
File[] filesInSourceFolder = sourceFolder.listFiles();
for (File file : filesInSourceFolder) {
if (file.isFile()) {
boolean moved = file.renameTo(new File(destinationFolder, file.getName()));
if (!moved) {
System.out.println("移动失败: " + file.getAbsolutePath());
}
}
}
}