java将一个文件夹下的内容复制到另一个文件夹下

package com.huangxt.io;

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

/**
 * @Title: CopyDir
 * @Description:复制一个文件夹的内容到另一个文件夹
 * @Auther: huangxt
 * @Version: 1.0
 * @create 2019/6/18 15:24
 */
public class CopyDir {
    public static void copyDir(String sourcePath, String newPath) throws IOException {
        File file = new File(sourcePath);   //获取文件夹File对象
        String[] filePath = file.list();    //获取文件夹下所有内容的名称

        if (!(new File(newPath)).exists()) {  //判断要目标文件夹是否存在不存在则创建
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {  //循环遍历
            //判断是不是文件夹,是的话执行递归。file.separator 分隔符,如“/”
            if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
                copyDir(sourcePath  + file.separator  + filePath[i], newPath  + file.separator + filePath[i]);
            }
            //判断是不是文件,是的话旧的文件拷至新的文件夹下
            if (new File(sourcePath  + file.separator + filePath[i]).isFile()) {
                copyFile(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
            }

        }
    }

    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);//获取旧的文件File对象
        File file = new File(newPath);  //获取新的文件File对象并生成文件
        FileInputStream in = new FileInputStream(oldFile);  //
        FileOutputStream out = new FileOutputStream(file);

        byte[] buffer=new byte[2097152];
        int readByte = 0;
        //读取旧文件的流写入新文件里
        while((readByte = in.read(buffer)) != -1){
            out.write(buffer, 0, readByte);
        }

        in.close();
        out.close();
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in); //启用输入
        System.out.println("请输入源目录:");
        String sourcePath = sc.nextLine();  //
        System.out.println("请输入新目录:");
        String path = sc.nextLine();

        //String sourcePath = "D://aa";
        //String path = "D://bb";

        copyDir(sourcePath, path);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值