递归遍历目录及文件

我电脑上有两个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文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值