IO流 文件复制

import java.io.*;

public class CopyFile2 {
    public static void main(String[] args) throws IOException {
        copyFileName("E:\\图片", "E:\\");
    }

    // 将文件1复制到文件2的目录下
    public static void copyFileName(String s1, String s2) throws IOException {
        File file1 = new File(s1);
        if (!file1.exists()) {  // 文件1不存在,退出
            return;
        }
        String name1 = file1.getName();
        if (file1.getParent().equals(s2)) {  // 第一次处理同名情况,加" - 副本"
            if (file1.isFile()) {
                String[] split = name1.split(".");  // 处理特殊名文件夹,如"fd.fr.txt"
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < split.length - 1; i++) {
                    sb.append(split[i]);
                }
                name1 = sb.toString() + " - 副本" + split[split.length - 1];
            } else {
                name1 += " - 副本";
            }
        }
        File file2 = new File(s2 + name1);
        copyFiles(file1, file2);
    }

    // 将文件1复制到文件2,file1与file2同级
    public static void copyFiles(File file1, File file2) throws IOException {
        if (file1.isFile()) {  // 文件1是文件,复制
            copyFile(file1, file2);  // 复制文件
            return;
        }
        // file1是文件夹,创建file2文件夹
        file2.mkdir();
        File[] files = file1.listFiles();  // 得到文件夹1的目录
        if (files != null) {
            for (File file1_1 : files) {  // 遍历目录
                copyFiles(file1_1, new File(file2, file1_1.getName()));  // 递归复制
            }
        }
    }
    // 将文件1复制到文件2
    public static void copyFile(File file1, File file2) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, read);
        }
        bis.close();
        bos.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值