File类和FileInputStream、FileOutputStream共同完成目录的复制

代码如下(示例):

import java.io.*;

public class DirectoryCopy {
    public static void main(String[] ages){
        //源目录
        File stateFile = new File("E:\\王志海老师大三下学期");
        //目标目录
        File destFile = new File("D:\\");
        //调用拷贝方法
        CopyDis(stateFile,destFile);

    }

    private static void CopyDis(File stateFile, File destFile) {
        if(stateFile.isFile()){//如果是源目录是文件
            //创建流文件
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(stateFile);
                //获取目标文件的路径  
                String strDest = (destFile.getAbsolutePath().endsWith("\\")
                        ? destFile.getAbsolutePath()
                        : destFile.getAbsolutePath()+"\\")//判断目标路径最后一位是否是“\\”结尾
                        +stateFile.getAbsolutePath().substring(3);//获得源目录地址的第三位以后的地址

                fos = new FileOutputStream(strDest);

                //开始边读边写
                byte[] bytes = new byte[1024*1024];
                int readCount = 0;
                while((readCount = fis.read(bytes)) != -1){
                    fos.write(bytes,0,readCount);
                }

                fos.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }
        //如果源目录不是文件,将运行到这里
        File[] files = stateFile.listFiles();
        for (File file : files){
            if(file.isDirectory()){//判断是否是目录
                String srcDir = file.getAbsolutePath();
                String dirDest = (destFile.getAbsolutePath().endsWith("\\")
                        ? destFile.getAbsolutePath()
                        : destFile.getAbsolutePath()+"\\")
                        +srcDir.substring(3);
                File dirFIle = new File(dirDest);
                if (!dirFIle.exists()){//判断文件是否存在
                    dirFIle.mkdirs();
                }
            }
            CopyDis(file,destFile);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值