输入两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中

学习过程中自己记录一下

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test3 {
    /*
     * 从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
     */
    static BufferedReader br;

    public static void main(String[] args) throws IOException {
        File src = getDir(); // 获取源文件
        File dest = getDir(); // 拷贝到目的文件夹中
        br.close();
        if (src.equals(dest)) {
            System.out.println("目标文件夹是源文件夹的子文件夹!");
        } else {
            copyFile(src, dest);
        }
        
    }

    public static File getDir() {
        try {
            // 不用自动关流写法,否则第二个路径无法输入
            br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("请输入一个文件夹路径");
            while (true) {
                String line = br.readLine();
                File dir = new File(line);
                if (!dir.exists()) {
                    System.out.println("不存在!重输:");
                } else if (dir.isFile()) {
                    System.out.println("输入的不是文件夹,请重新输入:");
                } else {
                    return dir;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null; 
    }

    /**
     * 拷贝带内容的文件夹 1.返回值类型void 2.参数列表File src, File dest
     * 
     * @throws IOException
     */
    public static void copyFile(File src, File dest) throws IOException {
        File newDir = new File(dest, src.getName());
        newDir.mkdirs();
        File[] subFiles = src.listFiles(); // 获取到原文件夹中所有的文件和文件夹
        for (File subFile : subFiles) {
            if (subFile.isFile()) {
                try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(subFile));
                        BufferedOutputStream bos = new BufferedOutputStream(
                                new FileOutputStream(new File(newDir, subFile.getName())));) {
                    int len;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else { // 否则是文件夹
                copyFile(subFile, newDir);
            }
        }
    }
}

========================================Talk is cheap, show me the code=======================================

猜你喜欢

转载自blog.csdn.net/qq_34115899/article/details/80814839