java 实现复制文件到指定目录

 将resource下的目录及文件,复制一份到指定目录,代码实现

import cn.hutool.core.io.FileUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.File;
import java.io.IOException;

/**
 * @author Lenovo
 */
public class StaticResourcesInit {
/**
     * 将resource下的目录,复制一份到指定目录
     * @param resourcePath resource下的目录,会读取下面的文件(不包含本身)
     * @param newRootPath 新的根目录
     * @param force 是否强制刷新,true表示会删除新的根目录下的所有文件
     */
    public void copyResources(String resourcePath,String newRootPath,boolean force) {
        File newRootFile = new File(newRootPath);
        if(newRootFile.exists() && force) {
            System.out.println("删除新的根目录"+newRootPath+":"+ FileUtil.del(newRootFile));
        }
        String rootPath = this.getClass().getClassLoader().getResource("static").getPath();
        if("\\".equals(File.separator)) {
            if(rootPath.startsWith("/")) {
                rootPath = rootPath.substring(1);
            }
            rootPath = rootPath.replaceAll("/","\\\\");
        }
        System.out.println("项目根目录:"+rootPath);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources("classpath:"+resourcePath+"/**");
            if(null!=resources || resources.length>0) {
                for (Resource resource : resources) {
                    File file = resource.getFile();
                    String newFilePath = file.getPath().replace(rootPath,newRootPath);
                    File newFile = new File(newFilePath);
                    if(!newFile.exists()) {
                        FileUtil.copy(file,newFile,true);
                        System.out.println("源文件:"+file.getAbsolutePath()+"已复制到:"+newFile.getAbsolutePath());
                    } else {
                        System.out.println("文件"+newFile.getAbsolutePath()+"已存在,不需要处理...");
                    }
                    // FileUtil.copy(file,FileUtil.newFile(file.getPath().replace(rootPath,newRootPath)),true);
                }
                System.out.println("resource下"+resourcePath+"目录下(不包含本身)的文件已全部复制到"+newRootPath);
            } else {
                System.out.println("未读取到"+resourcePath+"目录或目录下没有任何文件");
            }
        } catch (IOException e) {
            System.out.println("读取目录:"+resourcePath+"异常,"+e.getMessage());
            e.printStackTrace();
        }
}
    public static void main(String[] args) {
        new StaticResourcesInit().copyResources("static","D:\\test",true);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值