从键盘接收两个文件夹路径,把其中一个文件夹(包含内容),拷贝到另一个文件夹中

package cn.it.text;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;

/*
 * 1.从键盘接收两个文件夹路径,把其中一个文件夹(包含内容)
 *    拷贝到另一个文件夹中
 */
public class Test1 {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        String pathname1 = "";
        String pathname2 = "";
        while (true) {

            // 获取文件夹路径

            System.out.println("请输入文件夹路径1:");
            pathname1 = scan.nextLine();
            System.out.println("请输入文件夹路径2:");
            pathname2 = scan.nextLine();

            // 创建两个文件对象
            File file1 = new File(pathname1);
            File file2 = new File(pathname2);

            // 判断文件是否存在
            if (!(file1.exists() && file2.exists())) {
                System.out.println("你输入的文件夹路径错误!");
                // 跳出本层循环,重新输入
                continue;
            }
            // 判断是否是文件夹
            if (!(file1.isDirectory() && file2.isDirectory())) {
                System.out.println("你输入的不是文件夹路径!");
                continue;
            }

            // 创建输入输出流对象
            fuzhi(file1, file2);
            break;

        }

    }

    public static void fuzhi(File file1, File file2) throws Exception {
        //在目标文件中创建原文件夹
        //File类的构造方法File(File file,String name)
        File newFile=new File(file2,file1.getName());
        //创建文件夹,文件夹的路径在构造方法中给出,如果存在文件夹,就不再创建
        //如果不存在,就创建文件夹
        newFile.mkdir();
        
        //获取源文件夹中的文件目录
        File[] fileArr=file1.listFiles();
        
        //遍历数组
        for(File f:fileArr) {
            //如果是文件夹,就递归调用
            if (f.isDirectory()) {
                fuzhi(f, newFile);
            }else {
                //如果是文件,就使用IO流
                BufferedInputStream in=new BufferedInputStream(new FileInputStream(f));
                BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File(newFile,f.getName())));
                int b;
                while((b=in.read())!=-1) {
                    out.write(b);
                }
                in.close();
                out.close();
            }
        }
            
    }

}

猜你喜欢

转载自www.cnblogs.com/zhilili/p/10699897.html