java-> 利用IO操作与递归实现目录的复制
1 public class CopyDir { 2 3 public static void main(String[] args) { 4 copyDir(new File("d:\\a"), new File("d:\\b")); 5 } 6 7 8 //file1为被复制目录, file2为目标目录 9 public static void copyDir(File file1 ,File file2) { 10 //目标目录不存在则创建 11 if(!file2.exists()) { 12 file2.mkdir(); 13 } 14 //将源目录所有对象取出存入File[]数组中 15 File[] fList =file1.listFiles(); 16 //遍历源目录 17 for (File f : fList) { 18 //当子对象为目录时在目标目录中创建此目录 19 if(f.isDirectory()) { 20 File file =new File(file2,f.getName()); 21 file.mkdir(); 22 //调用自己 23 copyDir(f, file); 24 }else if(f.isFile()) { 25 //当子对象为文件时用字节流读取并写入目标目录中(复制) 26 BufferedInputStream bis = null ; 27 BufferedOutputStream bos = null; 28 try { 29 bis = new BufferedInputStream(new FileInputStream(f)); 30 bos = new BufferedOutputStream(new FileOutputStream(new File(file2,f.getName()))); 31 int len = 0; 32 byte[] bytes = new byte[1024]; 33 while((len = bis.read(bytes)) != -1) { 34 bos.write(bytes, 0, len); 35 } 36 } catch (IOException e) { 37 throw new RuntimeException("操作失败!"); 38 }finally { 39 try { 40 bis.close(); 41 bos.close(); 42 } catch (IOException e) { 43 throw new RuntimeException("关闭失败!"); 44 } 45 } 46 } 47 } 48 } 49 }