java复制文件夹
一、复制单级文件夹
package com.itbianma02; import java.io.*; public class Demo { public static void main(String[] args) throws IOException { File srcFolder=new File("D:\\资料库\\人事"); String srcFolderName= srcFolder.getName(); File desFolder=new File("myDemo",srcFolderName); if (!desFolder.exists()){ desFolder.mkdir(); } File[] listFiles=srcFolder.listFiles(); for(File srcFile:listFiles){ String srcFileName=srcFile.getName(); File desFile=new File(desFolder,srcFileName); copyFile(srcFile,desFile); } } private static void copyFile(File srcFile, File desFile) throws IOException { BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(desFile)); byte[] bys=new byte[1024]; int len; while ((len= bis.read(bys))!=-1){ bos.write(bys,0,len); } bis.close(); bos.close(); } }
二、复制多级文件夹
package com.itbianma02; import java.io.*; public class Demo1 { public static void main(String[] args) throws IOException { File srcFile=new File("D:\\资料库\\需求"); File desFile=new File("myDemo"); copyFolder(srcFile,desFile); } private static void copyFolder(File srcFile, File desFile) throws IOException { if (srcFile.isDirectory()){ String srcFolderName= srcFile.getName(); File newFolder=new File(desFile,srcFolderName); if(!newFolder.exists()){ newFolder.mkdir(); } File[] fileArray=srcFile.listFiles(); for(File file:fileArray){ copyFolder(file,newFolder); } }else{ File newFile=new File(desFile,srcFile.getName()); copyFile(srcFile,newFile); } } private static void copyFile(File srcFile, File desFile) throws IOException { BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(desFile)); byte[] bys=new byte[1024]; int len; while ((len= bis.read(bys))!=-1){ bos.write(bys,0,len); } bis.close(); bos.close(); } }
三、复制文件的异常处理
1、标准方法
2、JDK7之后的改进
3、JDK9之后的改进