黑马程序员技术交流社区

标题: 复制文件夹及其中的内容,大家看一下哪里可以改进 [打印本页]

作者: 天黑偷牛    时间: 2014-8-1 19:47
标题: 复制文件夹及其中的内容,大家看一下哪里可以改进
public static void copyFloder(String oldPath,String newPath) throws IOException{
                (new File(newPath)).mkdirs();//创建文件夹
                File f = new File(oldPath);
                String temp = null;
               
                if(!oldPath.endsWith(f.separator)){
                        oldPath = oldPath+f.separator;
                }
       
                //遍历当前文件夹
                File[] files = f.listFiles();
                for(File file:files){
                        //判断newPath是否是以目录分隔符结尾
                        if(newPath.endsWith(file.separator)){
                                temp = newPath+file.getName();
                        }else{
                                temp = newPath+file.separator+file.getName();
                        }
                        if(file.isFile()){
                                //复制到新目录下
                                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(oldPath+file.getName()));
                                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(temp));
                               
                                byte[] by = new byte[1024];
                                int len = 0;
                                while((len=bis.read(by))!=-1){
                                        bos.write(by);
                                        bos.flush();
                                }
                                bos.close();
                                bis.close();
                        }
                       
                        if(file.isDirectory()){
                                //如果是文件夹,那么就递归
                                copyFloder(oldPath+file.getName()+file.separator,temp+file.separator);
                        }
                       
                }
        }







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