黑马程序员技术交流社区

标题: 复制多级目录 [打印本页]

作者: 以梦为码    时间: 2015-7-16 19:13
标题: 复制多级目录
昨天没网,今天发上来。
//复制多级目录
/*分析:
1、目录下包含有目录和文件
2、递归实现这个操作,判断目录就是创建,是文件就创建并拷贝*/
public class Copy {
        public static void main(String[] args){
                File source=new File("f:"+File.separator+"wq");//原文件
                File target=new File("h:"+File.separator);//目标路径
            copydir(source,target);
        }
        //拷贝目录
        private static void copydir(File source,File target){
                //判断soure
                if(source.isDirectory()){
                        //是目录
                        //在target下创建同名目录
                        File dir=new File(target,source.getName());
                        dir.mkdirs();
                        //遍历soure下所有的子文件,将每个子文件作为source,将新的创建的目录作为target进行递归
                        File[] f=source.listFiles();
                        for(File file:f){
                                copydir(file,dir);
                        }
                }else{
                //是文件
                        //在target目录下创建同名文件,然后用流实现文件拷贝
                        File file=new File(target,source.getName());
                        copyFile(source,file);
                }
        }
        //拷贝文件
        private static void copyFile(File source,File file){
                //创建流对象
                InputStream is=null;
                OutputStream os=null;
                try {
                        is = new FileInputStream(source);
                        os = new FileOutputStream(file);

                        // 基本读写操作
                        byte[] bys = new byte[1024];
                        int len = 0;
                        while ((len = is.read(bys)) != -1) {
                                os.write(bys, 0, len);
                        }
                } catch(IOException e){
                        throw new RuntimeException("复制失败");
                }finally {
                        try{
                        if (os != null) {
                                os.close();
                        }
                        }catch(IOException e){
                               
                        }
                       
                        try{
                        if (is != null) {
                                is.close();
                        }
                        }catch(IOException e){
                               
                        }
                }
        }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2