Java 复制文件夹及文件

这里用到了两种复制文件夹及文件的方法

方法1:逐层复制文件夹&文件
参考博客1

@Controller
public class UploadController {
    @Value("${upload.path}")
    private String uploadPath; // 文件上传路径, 在 application.properties 中定义
    @Value("${report.output}")
    private String reportOutput;// PDF保存路径, 在 application.properties 中定义
    @Value("${source.path}")
    private String sourcePath; //文件处理的路径, 在 application.properties 中定义
    @Value("${static.path}")
    private String staticPath; //模板文件存放的路径, 在 application.properties 中定义
    @RequestMapping("/hello")
    @ResponseBody
     public  String hello() throws IOException, JRException{
        File f1 = new File(uploadPath); //创建文件对象
        File f2 = new File(sourcePath); 
        File f3 = new File(staticPath);
        if(!f2.exists()) {
            f2.mkdirs();
        }
        copyFolder(f1,f2);
        copyFolder(f3,f2);
     return sourcePath
     }
     private static void copyFolder(File oldFile, File newFile) throws IOException{
        if(oldFile.isDirectory()){
            File temFile = new File(newFile, oldFile.getName());
            // 创建目录前判断目录是否存在
            if(!temFile.exists()){
                temFile.mkdirs();
            }
            File[] files = oldFile.listFiles();
            for(File f : files){
            	//递归,继续搜索
                copyFolder(f,temFile);
            }
        }
        if(oldFile.isFile()){
            //复制文件前创建复制文件的对象,再复制文件
            File temFile = new File(newFile, oldFile.getName());
            copyFile(oldFile, temFile);
        }
    }
    private static void copyFile(File oldFile, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(oldFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));

        byte[] bys =new byte[1024];
        int len = 0;
        while((len = bis.read(bys)) != -1){
            bos.write(bys,0,len);
        }

        bos.close();
        bis.close();
    }

方法2:使用FileUtils.copyDirectory函数操作文件对象
FileUtils的详细使用方法可见链接1博客2

'''
略
'''
    public  String hello() throws IOException, JRException{
        File f1 = new File(uploadPath); //创建文件对象
        File f2 = new File(sourcePath);
        File f3 = new File(staticPath);
        if(!f2.exists()) {
            f2.mkdirs();
        }
        try {
            FileUtils.copyDirectory(f1, f2); //直接复制
            FileUtils.copyDirectory(f3, f2);
        } catch (IOException e) {e.printStackTrace();}
        return sourcePath;
    }

总结,建议能用轮子不要重复造,避免写成裹脚布

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值