• 五、java IO--通过字节流拷贝文件夹


    package cn.edu.hrbeu.io.file;
    
    import java.io.File;
    
    /**
     * 文件夹的拷贝
     * 1、当为文件时-->直接拷贝
     * 2、当为文件夹时-->创建文件夹-->递归查找子孙级
     */
    public class CopyDir {
    
        public static void main(String[] args) {
            String srcPath = ("F:/srcDir");
            String destPath = ("F:/destDir");
            copyDir(srcPath,destPath);
        }
        /**
         * 拷贝文件夹
         * @param srcPath
         * @param destPath
         */
        public static void copyDir(String srcPath,String destPath){
            File src = new File(srcPath);
            File dest = new File(destPath);
            if (src.isDirectory()){    //1、如果是文件夹    
    //      Creates a new File instance from a parent pathname string(destPath)
    //      and a child pathname string(src.getName()).
                dest = new File(destPath,src.getName());    //在路径destPath中新建一个src.getName()子目录
                dest.mkdirs();    //Creates the directory named by this abstract pathname(dest)        
            }
            copyDirDetail(src,dest);    
        }
        /**
         * 拷贝文件夹的细节实现(单独提出需要递归的部分,方便递归)
         * @param src
         * @param dest
         */
        public static void copyDirDetail(File src,File dest){
            if (src.isFile()) {        //2、如果是文件
                CopyFile.copyFile(src,dest);
            }else if (src.isDirectory()) {    //1、如果是文件夹
                dest.mkdirs();    //建立一个新的子目录
                for(File sub:src.listFiles())
                    copyDirDetail(sub,new File(dest,sub.getName()));//3、递归查找子孙级
            }
        }
    }
  • 相关阅读:
    面向对象
    面向对象
    面向对象
    面向对象
    面向对象
    面向对象
    面向对象
    面向对象
    3.1
    面向对象
  • 原文地址:https://www.cnblogs.com/jiaoqiang/p/8378616.html
Copyright © 2020-2023  润新知