java文件的复制(含目录)

import org.junit.Test;

import java.io.*;

public class CopyTest {
    @Test
    public void test1(){
       dir("xxx","xxx"); //输入原文件的路径和目标路径
        //copy(file);
    }

    private void dir(String src,String des) {
        File file = new File(src);   //获取源目录文件
        File[] files = file.listFiles(); //展开到数组
        if(files == null){
            return;
        }
       if(!(new File(des).exists()))
           new File(des).mkdirs();  //对于已经确定是目录的外部des先创建目录
        for (int i = 0; i < files.length; i++) {  //对des内部的文件遍历
            if (files[i].isFile()) {        //判断是文件还是目录
               copy(files[i].getPath(),des+File.separator+files[i].getName());//文件的当前路径作为源路径,目标路径即文件名
            } else if (files[i].isDirectory()){
              dir(files[i].getPath(),des+File.separator+files[i].getName()); // 子目录必须也得重新统计, 递归调用,目标路径加上文件名称作为下次迭代的新路径
            }
        }

    }

    public void copy(String src,String des){
        FileInputStream fio =null;
       //BufferedInputStream bio = null;

        FileOutputStream foo = null;
       //BufferedOutputStream boo = null;

        try {
            fio =new FileInputStream(src);
           // bio = new BufferedInputStream(fio);

            foo = new FileOutputStream(des);
           // boo = new BufferedOutputStream(foo);
            byte[] ch = new byte[8192];
           int n;
            while((n=fio.read(ch))!=-1){
                foo.write(ch,0,n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fio!=null){
                try {
                    fio.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(foo!=null){
                try {
                    foo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值