文件夹的拷贝

通过使用Java的文件字节流拷贝文件或文件夹,file1->file2

注意:

  • 无论是文件还是文件夹,都可以实现拷贝
  • file2文件夹内部的原内容继续保存且不变
  • 若文件夹file2不存在则会自动创建
  • 该函数通过递归调用实现
  • 由于使用的是文件字节流,所以无论是文本文件还是图片或视频都可以实现拷贝
java 复制代码
public static void copyDirectory(File file1,File file2) {	//拷贝函数:file1->file2
        if (!file1.exists() | file1 == null) {
            return;
        }
        if (!file2.exists()) {
            file2.mkdirs();
        }
        String name = file1.getName();
        File file3 = new File(file2.getAbsoluteFile() +"\\"+ name);

        if (file1.isFile()) {
            try (FileInputStream inputStream = new FileInputStream(file1);
                 FileOutputStream outputStream = new FileOutputStream(file3)) {
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        file3.mkdir();
        File[] files = file1.listFiles();
        for (int i = 0; i < files.length; i++) {	//递归调用
            copyDirectory(files[i], file3);
        }

    }

测试

java 复制代码
public static void main(String[] args) {	//测试
        File file = new File("target");
        File file2 = new File("target2");	//文件夹target2的原内容不变
        copyDirectory(file,file2);
    }
相关推荐
java_nnnn15 分钟前
文件操作和IO
java
lsylalalala16 分钟前
多线程(4)
java·开发语言·多线程
小白不想画工图18 分钟前
银河麒麟V10系统安装QT5.12
linux·开发语言·qt·银河麒麟
吴声子夜歌43 分钟前
Guava——散列
java·guava
用户31268748772044 分钟前
AQS 到底怎么排队的?CLH 队列、state 与条件变量全链路拆解
java
Json____1 小时前
springboot开发高校选课管理系统:从零构建前后端分离的全栈实践
java·spring boot·后端·毕业设计·毕设·wwwoop.com
xcl09251 小时前
民宿预约系统开发实战:从需求分析到上线部署全流程解析
java·spring boot
IT_Octopus1 小时前
JSON 日志里的 `{“$ref“:“$.xxx“}`:从 fastjson 兼容包到原生 fastjson2 的迁移实录
开发语言·python·json
geovindu1 小时前
python:HandWriting Recognition using paddlepaddle
开发语言·后端·python·paddlepaddle
步行cgn1 小时前
为何以继承方式引入SpringBoot
java·spring boot·后端