zoukankan      html  css  js  c++  java
  • JavaSE:将某个目录下的所有内容,拷贝到另一个目录下

    代码示例:

     1 import java.io.*;
     2 
     3 public class CopyTest {
     4     public static void main(String[] args) {
     5         
     6         File srcDir = new File("./A");
     7         File tarDir = new File("./B");
     8         
     9         // 调用copyDir()方法,复制指定目录下的所有文件
    10         copyDir(srcDir,tarDir);
    11     }
    12     
    13     public static void copyDir(File srcDir, File tarDir) {
    14         
    15         if(!tarDir.exists()) {
    16             // 若目标目录不存在,则使用File类中的mkdir()创建目录
    17             tarDir.mkdir();
    18         }
    19         
    20         // 使用File类中的listFiles(),获取指定目录下的所有文件
    21         File[] files = srcDir.listFiles();
    22         
    23         for(File file : files) {
    24             if (file.isFile()) {
    25                 // 若是文件,则调用拷贝方法
    26                 copyFile(new File (srcDir + "\" + file.getName()), new File(tarDir + "\" + file.getName()));            
    27                 
    28             }else {
    29                 // 若是目录,则使用递归
    30                 copyDir(new File (srcDir + "\" + file.getName()), new File(tarDir + "\" + file.getName()));            
    31             }
    32         }
    33     }
    34     
    35     public static void copyFile (File srcFile, File tarFile) {
    36         
    37         BufferedInputStream bis = null;
    38         BufferedOutputStream bos = null;
    39         
    40         try {
    41             bis = new BufferedInputStream(new FileInputStream(srcFile));
    42             bos = new BufferedOutputStream(new FileOutputStream(tarFile));
    43             
    44             byte[] buffer = new byte[1024];
    45             int len = 0; // 用于储存读取到的字节的个数
    46             while( (len = bis.read(buffer)) != -1 ){
    47                 bos.write(buffer,0,len);
    48             }
    49         }catch (FileNotFoundException e){
    50             e.printStackTrace();
    51         }catch (IOException e) {
    52             e.printStackTrace();
    53         }finally {
    54             if (bos != null) {
    55                 try {
    56                     bos.close();
    57                 } catch (IOException e) {
    58                     e.printStackTrace();
    59                 }
    60             }
    61             if (bis != null) {
    62                 try {
    63                     bis.close();
    64                 } catch (IOException e) {
    65                     e.printStackTrace();
    66                 }
    67             }
    68         }
    69     }
    70 }
  • 相关阅读:
    Struts2项目问题及解决方式
    CSS样式编写案例
    第二个项目总结
    CSS布局中的问题解决方式
    CSS3中的Flexbox弹性布局(二)
    CSS3中的Flexbox弹性布局(一)
    python----递归函数
    python----函数进阶
    python----函数
    python----装饰器
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/14929780.html
Copyright © 2011-2022 走看看