我电脑上有两个maven仓库,我想合并在一起,就打算用递归的方式跑一遍,并记录下来。
递归:简单来说一句话就是自己调用自己。具体的详细描述,可以直接搜索‘递归’两个字,会有更详细的介绍。
注意❗️:正是自己调用自己,会陷入死循环,一定要有结束条件!另外递归很消耗内存,基本上都可以有别的方案代替。
代码如下:
// 将一个文件夹下的所有文件及文件夹复制到另一个文件夹下
public static void main(String[] args) {
String source = "/Users/xxx/files/tmp/source"; // 待复制文件路径
String target = "/Users/xxx/files/tmp/tmp2/target"; // 目标路径
backupTo(source, target, false);
}
public static void backupTo(String source, String target) {
// 路径校验
File sourceFile = new File(source);
File targetFile = new File(target);
if(!sourceFile.exists()){
// 在此返回错误信息
System.out.println("传入的目录或者文件不存在");
return;
}
//目录
if (sourceFile.isDirectory()) {
if (isMkdir) { // 去掉source路径,只复制source里面的内容
targetFile = new File(targetFile, sourceFile.getName());
}
targetFile.mkdir();
// 列出目录下的所有文件包括目录
File[] files = sourceFile.listFiles();
for (File f : Objects.requireNonNull(files)) {
if(f.isDirectory()){
backupTo(f.toString(), targetFile.toString(), true); // 在此递归
}else if (!f.getName().equals(".DS_Store")){ // 因为我是mac电脑,需要过滤此垃圾文件
// copy文件,存在则跳过
copyFile(f, new File(targetFile.toString(), f.getName()));
}
}
} else {
copyFile(sourceFile, targetFile);
}
System.out.println("copy完成");
}
private static void copyFile(File sourceFile, File targetFile){
FileInputStream intPut = null;
FileOutputStream outPut = null;
try {
intPut = new FileInputStream(sourceFile);
outPut = new FileOutputStream(targetFile);
byte[] buf = new byte[1024];
int len;
while ((len = intPut.read(buf)) != -1) {
outPut.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
outPut.close();
intPut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
效果:可以把m2仓库里的jar完全的复制到m1中,其中可以在复制文件的地方加一些判断,过滤掉不想要的文件,比如.lastUpdate文件。