java I/O流 使用File,FileInputStream,FileOutputStream类复制目录

在学习了java的I/O之后,写了一个复制目录的小练习。

package com.exception.file01;

import java.io.*;

public class CopyDirectory {
    public static void main(String[] args) throws IOException {
        CopyDire copyDire = new CopyDire();
        copyDire.copyDire("E:\\LOL","D:\\LOL"); // 要复制的目录和要复制到那个位置

    }
}

class CopyDire {
    public void copyDire(String in, String out) throws IOException {
        File f1 = new File(in);  // "E:\\LOL"
        File fn = new File(out);  // "D:\\LOL"
        if (!fn.exists()) {  // 如果要没有这个目录就新建
            fn.mkdirs();
        }
        File[] f2 = f1.listFiles();  // 读取这个目录下的子文件返回File对象组成的数组
        // System.out.println(f2.length);
        for (File f : f2) {  // 将File对象循环
            if (f.isDirectory()) {  // 如果是目录 使用递归
                // System.out.println(f.getAbsolutePath()+"+++"+fn.getAbsoluteFile() + "\\" + f.getName());
                copyDire(f.getAbsolutePath(),fn.getAbsoluteFile() + "\\" + f.getName());

            }else if(f.isFile()){  // 如果是文件 就复制
                FileInputStream fis = null;
                FileOutputStream fos = null;
                fis = new FileInputStream(f.getAbsoluteFile());
                fos = new FileOutputStream(fn.getAbsoluteFile() + "\\" + f.getName());
                System.out.println(fn.getAbsoluteFile() + "\\" + f.getName());

                byte[] bytes = new byte[1024 * 1024];   // 1mb
                int readCount = 0;
                while ((readCount = fis.read(bytes)) != -1) {
                    fos.write(bytes, 0, readCount);
                }
                // 输出流要刷新
                fos.flush();
                // 关闭管道
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }
        }
    }
}

少年易老学难成,一寸光阴不可轻

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值