文件夹复制的Java实现

目标:将文件夹copyTest 复制到 目标文件夹内。

分析:这里需要考虑两部分 。

  1. 如何复制文件夹和文件:新建一递归方法
    a.如果是文件夹,继续调用该方法;
    b.如果是文件,直接利用流复制文件内容。

  2. 意外情况:
    a.当源文件夹和目标文件夹在同一个文件夹内时;
    b.当目标文件夹为源文件夹子文件夹时。

代码实现:

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

public class FileCopy {
    public static void main(String[] args) {
        String src = "E:\\copyTest\\test";
        String dest = "E:";

        try {
            copyTo(src, dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void copyTo(String src, String dest) throws IOException {
        // 目标文件夹 为 源文件夹的子文件夹时,返回
        if(dest.indexOf(src)!=-1){
            System.out.println("操作无效,
            目标文件夹为源文件夹子的文件夹!");
            return;
        }

        File srcFile = new File(src);
        // 这样定义destFile为的是把源文件夹一起复制过来
        File destFile = new File(dest,srcFile.getName());

        // 源文件夹和目标问价夹位于同一文件夹内时,
        // 目标文件夹为原文件夹的副本
        if(destFile.exists()){
            destFile = new File(dest, srcFile.getName()
             + " - 副本");
        }

        destFile.mkdirs();

        // 复制文件夹的内容
        copyFiles(srcFile,destFile);

    }

    private static void copyFiles(File srcFile, File destFile)
            throws IOException {

        // 首先创建最外层文件夹(不存在,才创建)
        if (!destFile.exists()) {
            destFile.mkdirs();
        }

        // 获取源文件夹File数组,并遍历数组,分别作判断
        File[] srcFiles = srcFile.listFiles();
        for (File f : srcFiles) {
            // 文件夹,则创建文件夹,并继续该方法
            if (f.isDirectory()) {
            // 此时,源文件夹为初始源文件夹的子文件夹
            // 目标文件夹为初始目标文件夹的子文件夹
                copyFiles(f, new File(destFile, f.getName()));
            } else {
                // 文件,则使用文件输入输出流复制文件内容

                BufferedInputStream bis = 
                new BufferedInputStream(new FileInputStream(f));
                BufferedOutputStream bos = 
                new BufferedOutputStream(new FileOutputStream(
                    new File(destFile,f.getName())));


                byte[] buf = new byte[1024];
                int len;
                while((len=bis.read(buf))!=-1){
                    bos.write(buf,0,len);
                }

                bos.close();
                bis.close();
            }
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值