使用Java的IO复制多级目录
主要步骤
-
新建源文件和目标文件
//要复制的源文件 File srcFile=new File("C:\\My\\WorkSpace\\VScode"); //目标文件 File destFile=new File("D:\\");
-
调用copyFile()方法完成复制
copyFile(srcFile,destFile);
-
实现copyFile()方法
private static void copyFile(File srcFile, File destFile) { int length=destFile.getAbolutePath().length();//要截取源目录的长度 if(srcFile.isFile()){ FileInPutStream in=null; FileOutPutStream out=null; try{ in=new FileInPutStream(srcFile); out=new FileOutPutStream(destFile.getAbsolutePath()+srcFile.getAbsolutePath().subString(length)); int readCount=0; byte[] bytes=new byte[1024*1024];//每次读取1M数据 while(-1!=(readCount=in.read(bytes))){ out.writer(bytes,0,readCount);//把读到的数据全部写出 } out.flush(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally{ if(in!=null){ try{ in.close(); }catch (IOException e){ e.printStackTrace(); } } } if(out!=null){ try{ out.close(); }catch (IOException e){ e.printStackTrace(); } } } return; } //程序走到这里说明srcFile是一个目录 File files=srcFile.listFiles();//获取当前目录下的子目录或文件 for(File file:files){ //如果是目录就创建这个目录 if(file.isDirectory()){ //使用字符串拼接拿到新建目录的名字 String dirName=destFile.getAbsolutePath()+file.getAbsolutePath().subString(length); File newDir=new File(dirName); if(!newDir.exists()){ newDir.mkdirs(); } } //这里使用递归来复制flle copyFile(file,destFile); } }