IO流之文件的复制

package com.qiang.IO5;

import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        File source = new File("D:/projects/aa");

        File target = new File("D:/Ideal wrok space/tt");

        copy(source,target);
    }

    public static  void  copy(File source,File target){
        if (!source.exists()){  //判断源文件路径是否存在
            return;
        }
        if (source.isFile()){
            //组合一个新的目标文件绝对路径
            File newFilePath = new File(target,source.getName());
            target.mkdirs();  //创建新的目标文件需要所有的父级别目录
            copyFile(source,newFilePath);
            return;
        }

        File[] files = source.listFiles();
        for (File f: files
             ) {
            //组合一个新的目标路径,使用原有的目标路径追加一个当前source文件加名字
            File newTargetPath = new File(target,source.getName());
            copy(f,newTargetPath);
        }
        //如果成行没有进入循环直接执行到这里表示当前的source所指向的路径是一个空文件夹,那么需要在目标位置创建这个文件夹
        File newTargetPath = new File(target,source.getName());
        newTargetPath.mkdirs();

    }



    private   static void  copyFile(File  sourcePath, File targetPath){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;


        try {
            fileInputStream = new FileInputStream(sourcePath);
            fileOutputStream = new FileOutputStream(targetPath);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len= fileInputStream.read(bytes))>=0){
                fileOutputStream.write(bytes, 0,len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (fileInputStream!= null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值