当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 使用 IO 流复制目录

使用 IO 流复制目录

2020年10月24日  | 移动技术网IT编程  | 我要评论
场景:要将 D 盘上的某个文件夹通过 IO 流复制到 E 盘下的某个文件夹中。实现:在一个 文件工具类中,通过 IO 流技术,运用递归算法,实现了一个简单的磁盘上文件夹的复制代码:public class FileUtil { /** * 复制目录 * * @param srcFile 源文件 * @param destFile 目标文件 */ public static void copyDir(File s

场景:要将 D 盘上的某个文件夹通过 IO 流复制到 E 盘下的某个文件夹中。

实现:
在一个 文件工具类中,通过 IO 流技术,运用递归算法,实现了一个简单的磁盘上文件夹的复制

代码:

public class FileUtil {

    /**
     * 复制目录
     *
     * @param srcFile       源文件
     * @param destFile      目标文件
     */
    public static void copyDir(File srcFile, File destFile) throws Exception{
        // 判断是否为文件
        if (srcFile.isFile()) {
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream((destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath()
                    : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3));

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

            fos.flush();
            fis.close();
            fos.close();
        } else {
            // 如果不是文件,则获取它的下级目录
            File[] files = srcFile.listFiles();
            if (null != files) {
                if (files.length > 0) {
                    for (File file : files) {
                        if (file.isDirectory()) {
                            String srcDir = file.getAbsolutePath();
                            String destDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath()
                                    : destFile.getAbsolutePath() + "\\") + srcDir.substring(3);

                            // 生成文件夹
                            File newFile = new File(destDir);
                            if (!newFile.exists()) {
                                newFile.mkdirs();
                            }
                        }
						
						// 递归调用
                        copyDir(file, destFile);
                    }
                }
            }
        }
    }
}

通过 main() 方法进行测试:

public static void main(String[] args) throws Exception{
    String srcFilePath = "D:\\docs";
    String destFilePath = "E:\\zzc\\test\\";

    File srcFile = new File(srcFilePath);
    if (!srcFile.exists()) {
        throw new RuntimeException("此文件路径不存在");
    }
    File destFile = new File(destFilePath);

    // 防止源文件夹中的路径名不会被生成(当遍历源文件夹第一个 File 为文件时,是不会生成 "ttt" 路径名)
    String path = (destFilePath.endsWith("\\") ? destFilePath : destFilePath + "\\") + srcFilePath.substring(3);
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }
    FileUtil.copyDir(srcFile, destFile);
}

我认为,这种场景很典型,所以,这里就把它给记录下来了~~

本文地址:https://blog.csdn.net/Lucky_Boy_Luck/article/details/109266155

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网