将目标文件夹中包含特定后缀的文件移动到同一个目录下
package com.andon;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
*
* @Author: GFC
* @Date: 2020年12月1日
* @Version: v1.0
*/
public class Test {
public static void main(String[] args) {
String srcPath = "/Users/GFC/Desktop/localRepository";
String targetPath = "/Users/GFC/Desktop/copy";
String suffixName = "jar";
String message = removeSrcToTarget(srcPath, targetPath, suffixName);
System.out.println(message);
}
/**
*
* @Description 将目标文件夹中包含特定后缀的文件移动到同一个目录下
* @param srcPath 源目录的路径
* @param targetPath 目标路径
* @param suffixName 后缀名
* @return
* @return String
* @throw
*/
public static String removeSrcToTarget(String srcPath, String targetPath, String suffixName) {
String message = null;
File srcFile = new File(srcPath);
// 判断目录是否存在
boolean exists = srcFile.exists();
if (!exists) {
message = "目录不存在!!!";
return message;
}
File targetFile = new File(targetPath);
boolean targetFileExists = targetFile.exists();
if (!targetFileExists) {
targetFile.mkdirs();
}
// 判断是否是目录
boolean directory = srcFile.isDirectory();
if (directory) {
// 是目录
// 遍历目录
File[] listFiles = srcFile.listFiles();
// 判断是否为空目录
int length = listFiles.length;
if (length == 0) {
message = "目录为空";
return message;
}
for (File file : listFiles) {
removeSrcToTarget(file.getPath(), targetPath, suffixName);
}
message = "复制完成";
return message;
} else {
// 是文件
// 判断结尾
String name = srcFile.getName();
if (name.endsWith(suffixName) || name.equalsIgnoreCase(suffixName)) {
try {
FileUtils.copyFileToDirectory(srcFile, targetFile);
System.out.println(srcFile + "复制成功.");
} catch (IOException e) {
e.printStackTrace();
System.out.println(srcFile + "复制失败.");
}
}
}
return message;
}
}
0条评论