Java文件夹中内容复制到另一文件夹不实现文件的覆盖

Java文件夹复制

package lab.lab2;
/**
 * @Title: CopyDir
 * @Description:复制一个文件夹的内容到另一个文件夹
 * @Auther: zzp
 * @Version: 1.0
 * @create 2020/4/17 15:24
 */
import java.io.*;
public class CopyDir {
    public static void copyDirectory(String oldPath, String newPath) throws IOException {
        String[] filePath = (new File(oldPath)).list(); //文件夹内文件的名字数组
        int newPathExist = 1;//记录初始状态下文件夹是否存在,存在为1,不存在为0
        if (!(new File(newPath)).exists()) {  //判断要目标文件夹是否存在不存在则创建,并将newPathExist置0
            (new File(newPath)).mkdir();
            newPathExist = 0;
        }
        if(newPathExist ==1){
            String[] filePath2 = (new File(newPath)).list();
            for (int i = 0; i < filePath.length; i++) {
                int k =0;//文件是否已在目标文件夹中存在 存在为1,不存在为0
                for(int j=0;j<filePath2.length;j++) {//新文件夹中是否存在相同的文件名 有则不复制
                    if(filePath2[j].equals(filePath[i])){
                        k=1;
                    }
                }
                if(k==0){
                    if ((new File(oldPath +"/" + filePath[i])).isDirectory()) { //判断是不是文件夹,是的话执行递归
                        copyDirectory(oldPath  + "/"  + filePath[i], newPath  + "/" + filePath[i]);
                    } else if (new File(oldPath  + "/" + filePath[i]).isFile()) {//判断是不是文件,是的话旧的文件拷至新的文件夹下
                        copyFile(oldPath + "/" + filePath[i], newPath + "/" + filePath[i]);
                    }
                }
            }
        }else{
            for (int i = 0; i < filePath.length; i++) {
                if ((new File(oldPath + "/" + filePath[i])).isDirectory()) {
                    copyDirectory(oldPath  + "/"  + filePath[i], newPath  + "/" + filePath[i]);
                } else if (new File(oldPath  + "/" + filePath[i]).isFile()) {
                    copyFile(oldPath + "/" + filePath[i], newPath + "/" + filePath[i]);
                }
            }
        }
    }

    public static void copyFile(String oldPath, String newPath) throws IOException {//复制文件函数
        FileInputStream fis = new FileInputStream(new File(oldPath));
        FileOutputStream fos = new FileOutputStream(new File(newPath));
        byte[] buf=new byte[2048];
        int a = 0;
        while((a = fis.read(buf)) != -1){
            fos.write(buf, 0, a);
        }
        fis.close();
        fos.close();
    }

    public static void main(String[] args) throws IOException {
        copyDirectory("D:\\a", "D:\\b");
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值