zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    看了前辈缠中说禅及其反响,忍不住想说些东西
    利弗莫尔的操盘精华篇
    缠中说禅:教你炒股票108课(转载)
    评温斯坦的炒股书(非常重要,常看看)
    本散女2
    使用PHP-GTK编写一个windows桌面应用程序
    php.exe php-cgi.exe php-win.exe的区别
    php调试利器之phpdbg
    yaf框架安装配置
    phalcon框架安装
  • 原文地址:https://www.cnblogs.com/miaoxingren/p/9523422.html
Copyright © 2011-2022 走看看