黑马程序员_多级目录的复制

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

利用IO流复制windows下的一个多级文件夹
1.目录下包含文件和文件夹
2.判断目录下的内容,如果是文件,就创建并拷贝,如果是文件夹,就创建。用递归实现。

例如我想把E盘下的eclipse文件夹复制到D盘
这里写图片描述
eclipse文件夹里有文件和文件夹,文件夹里还有文件和文件夹

import java.io.*;
public class Copy {
    public static void main(String[] args) {
        File source = new File("E:\eclipse");
        File target = new File("D:");
        copyDir(source,target);
    }

    public static void copyDir(File source,File target){
        //判断目录下是文件夹
        //创建新目录
        if(source.isDirectory()){
            File dir = new File(target,source.getName());
            //在target下建立同名目录
            dir.mkdirs();
            //遍历source下的所有子目录,将每个文件作为source,将新创建的目录作为target进行递归
            File[] files = source.listFiles();
            for(File file:files){
                copyDir(file,dir);
            }
        }else{//是文件,就在目录下创建同名文件,并用流操作实现文件拷贝
            File file = new File(target,source.getName());
            copyFile(source,file);
        }
    }

    //拷贝文件
    public static void copyFile(File source,File file){
        //创建流对象
        InputStream is = null;
        OutputStream os = null;
        try{
            is = new FileInputStream(source);
            os = new FileOutputStream(file);

            //读写基本操作
            byte[] bytes = new byte[1024];
            int len = 0;
            while((len = is.read(bytes))!= -1){
                os.write(bytes, 0, len);
            }
        }catch(IOException e){
            throw new RuntimeException("复制文件失败");
        }finally{
            try{
                if(os!=null)
                    os.close();
            }catch(IOException e){
                throw new RuntimeException("关闭资源失败");
            }finally{
                try{
                    if(is!=null)
                        is.close();
                }catch(IOException e){
                    throw new RuntimeException("关闭资源失败");
                }
            }
        }
    }
}

用IO流复制文件的速度比windows快,这里我创建的数组是1M的
不知道如果byte[] bytes = new byte[1024*10]的话会不会更快呢?

在复制大文件和文件夹上确实比windows快,所以当然要做一个工具类,以后拷大文件和文件夹就可以直接用啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值