Java:复制文件夹及子文件

package stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestStream {
    public static void main(String[] args) {
        copyFolder("d:/lol","e:/profiles/lol");
    }
    /**
     * @param srcFile 源文件
     * @param destFile 目标文件
     */
    public static void copyFile(String srcPath, String destPath) {
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);

        //缓存区,一次性读取1024字节
        byte[] buffer = new byte[1024];
        try (
                FileInputStream fis = new FileInputStream(srcFile);
                FileOutputStream fos = new FileOutputStream(destFile);
            )
        {
            while (true) {
                //实际读取的长度是actuallyReaded,有可能小于1024  
                int actuallyReaded = fis.read(buffer);
                // -1表示没有可读的内容了
                if(-1==actuallyReaded)
                    break;
                fos.write(buffer, 0, actuallyReaded);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @param srcPath  源文件夹
     * @param destPath 目标文件夹
     */
    public static void copyFolder(String srcPath, String destPath) {
        File srcFolder = new File(srcPath);
        File destFolder = new File(destPath);
        //源文件夹不存在
        if(!srcFolder.exists())
            return;
        //源文件夹不是一个文件夹
        if(!srcFolder.isDirectory())
            return;
        //目标文件夹是一个文件
        if(destFolder.isFile())
            return;
        //目标文件夹不存在,则创建一个
        if(!destFolder.exists())
            destFolder.mkdirs();

        //遍历源文件夹
        File[] files = srcFolder.listFiles();
        for (File f : files) {
            //如果是文件就复制
            if(f.isFile()) {
                File newDestFile = new File(destFolder,f.getName());
                copyFile(f.getAbsolutePath(), newDestFile.getAbsolutePath());
            }
            //如果是文件夹,就递归
            if(f.isDirectory()) {
                File newDestFolder = new File(destFolder,f.getName());
                copyFolder(f.getAbsolutePath(), newDestFolder.getAbsolutePath());
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值