简单实现复制整个目录(源码)

复制整个目录(源码)

关键字:FileFileInputStreamFileOutputStream

public class CopyDirectorys {

    /**
     * 以递归的方式拷贝整个目录
     * @param copyPath 需要拷贝的目录路径
     * @param newPath 新的目录
     * @throws Exception
     */
    public static void copy(String copyPath, String newPath) throws Exception {
        File file = new File(copyPath);
        File file1 = new File(newPath);
        if (!file.isDirectory() || !file1.isDirectory()) {
            // 自定义错误
            throw new FileIsNotDirectoryException("传入参数不是目录路径");
        }

        // 转为 绝对路径
        copyPath = file.getAbsolutePath();
        newPath = file1.getAbsolutePath();

        // 在新路径下创建目录 并返回新路径+文件名
        newPath = mkdir(newPath, file.getName());

        File[] files = file.listFiles();
        // 目录没有文件就返回
        if (files == null || files.length == 0) {
            return;
        }
        // 文件名
        String filename = "";
        for (File f : files) {
            filename = f.getName();
            if (f.isDirectory()) {
                // 是目录 就 递归拷贝
                copy(copyPath + "\\" + filename, newPath);
            } else {
                // 不是目录 就 复制文件
                copyFile(copyPath + "\\" + filename, newPath + "\\" + filename);
            }
        }
    }

    /**
     * 新建目录并返回新的路径
     *
     * @param path 需要添加目录的路径
     * @param name 目录名
     * @return 新的路径 原路径+目录名
     */
    private static String mkdir(String path, String name) {
        String newPath = path + "\\" + name;
        new File(newPath).mkdir();
        return newPath;
    }

    /**
     * 复制文件
     *
     * @param inputPath  需要复制的文件的路径
     * @param outputPath 写入文件的路径
     * @throws IOException
     */
    private static void copyFile(String inputPath, String outputPath) throws IOException {
        FileInputStream fis = new FileInputStream(inputPath);
        FileOutputStream fos = new FileOutputStream(outputPath);

        byte[] bytes = new byte[1024 * 1024];
        int count = 0;
        while ((count = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, count);
        }

        fis.close();
        fos.flush();
        fos.close();
    }
}
posted @ 2020-11-30 18:47  东郊  阅读(320)  评论(0)    收藏  举报