A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 以梦为码 中级黑马   /  2015-7-16 19:13  /  387 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

昨天没网,今天发上来。
//复制多级目录
/*分析:
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){
                               
                        }
                }
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马