JavaIO 文件夹复制

简单的文件夹的复制,注释中有说明。直接上代码。

package com.company.day09;

import java.io.*;

public class CopyDirectory {
//  将target文件复制到file文件夹中去。
    public static void createAndCopyFile(File file, File target) throws IOException {
        // 先创建文件,再写入。文件名与file中文件名相同
        File temp = new File(target.getPath() + "\\" + file.getName());
        // java7特性,自动管理资源
        try(BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(temp))){
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        }
    }
//  复制start到target中去
    public static void copy(File start, File target) throws IOException {
        // 如果要复制的是个文件。使得不是文件夹也可以调用此方法。如果执行只执行一次。
        if (start.isFile()) {
            // 那么直接创建该文件再写过去。
            createAndCopyFile(start, target);
            return;
        }
        // 如果要复制的是个文件夹。
        if (start.isDirectory()) {
            // 先在target中创建该文件夹。
            File directory = new File(target.getPath() + "\\" + start.getName());
            if (!directory.exists()){
                boolean mkdir = directory.mkdir();
                if (!mkdir)
                    throw new IOException("创建文件夹失败!");
            }
            // 然后遍历该文件夹。
            File[] files = start.listFiles();
            assert files != null;
            for (File file : files) {
                // 如果是文件夹,将递归。
                if (file.isDirectory()) {
                    copy(file, directory);
                }
                // 如果是文件,复制该文件。
                if (file.isFile()) {
                    createAndCopyFile(file, directory);
                }
            }
        }

    }

    public static void main(String[] args) {
        // 路径随意指定。
        File start = new File("day09");
        File target = new File("tmp");
        long begin = System.currentTimeMillis();
        try {
            copy(start, target);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis() - begin);
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值