美文网首页
递归遍历替换文件夹名称及文件名称

递归遍历替换文件夹名称及文件名称

作者: 1714bb66b1f9 | 来源:发表于2021-01-25 15:03 被阅读0次

1、递归遍历文件夹及子文件
2、替换文件夹及文件名称
上代码:

   private static String TEMPLATE_STR = "account-service";
    /**
     * 递归遍历文件夹,并替换文件夹及文件的名称
     *
     * @param path        遍历文件夹的起始位置
     * @param newPathName 新文件夹或新文件的名称
     */
    public void foreachAndReplaceFolder(String path, String newPathName) {
        File folder = new File(path);
        if (!folder.exists()) {
            log.info("文件不存在! path=" + path);
            return;
        }
        File[] fileArr = folder.listFiles();
        if (null == fileArr || fileArr.length == 0) {
            log.info("文件夹是空的! path=" + path);
            return;
        }

        for (File file : fileArr) {
            //若是文件夹,替换文件夹,
            if (file.isDirectory()) {
                //判断文件夹是否包含指定字符串,
                if (file.getName().contains(TEMPLATE_STR)) {
                    log.info("替换旧文件夹:{}", file.getName());
                    String newFilePath = file.getParent() + System.getProperty("file.separator") + file.getName().replaceAll(TEMPLATE_STR, newPathName);
                    file.renameTo(new File(newFilePath));
                    foreachAndReplaceFolder(newFilePath, newPathName);
                } else {
                    //不包含,继续递归
                    foreachAndReplaceFolder(file.getAbsolutePath(), newPathName);
                }
            } else {
                //是文件,判断文件名称是否包含指定字符串,
                if (file.getName().contains(TEMPLATE_STR)) {
                    String newFilePath = file.getParent() + System.getProperty("file.separator") + file.getName().replaceAll(TEMPLATE_STR, newPathName);
                    file.renameTo(new File(newFilePath));
                    log.info("替换旧文件:" + file.getName());
                }
            }
        }
    }

相关文章

网友评论

      本文标题:递归遍历替换文件夹名称及文件名称

      本文链接:https://www.haomeiwen.com/subject/cztizktx.html