A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

  1. package com.heima.test;

  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;

  9. /**
  10. *
  11. * 将一个文件夹复制到另一个文件夹中
  12. *
  13. */
  14. public class Test3 {
  15.         public static void main(String[] args) throws IOException {
  16.                 //获取两个文件夹路径
  17.                 File yuan = Test.getDir();
  18.                 File  des = Test.getDir();
  19.                 if(yuan.equals(des)){
  20.                         System.out.println("目标文件夹是源文件夹的子文件夹");
  21.                        
  22.                 }
  23.                
  24.                 //调用方法,进行复制
  25.                 method(yuan,des);
  26.                
  27.         }

  28.         public static void method(File yuan, File des) throws IOException {
  29.                 //在目标文件夹中创建原文件夹
  30.                 File newf = new File(des,yuan.getName());
  31.                 newf.mkdirs();
  32.                 //创建File数组,添加原路径下的文件夹和文件,遍历
  33.                 File[] f1 = yuan.listFiles();
  34.                
  35.                 if (f1 == null){
  36.                         return;
  37.                 }
  38.                 for (File f2 : f1) {
  39.                         //如果是文件的话,就复制
  40.                         if (f2.isFile()){
  41.                                 copy(newf, f2);
  42.                         }
  43.                        
  44.                         //如果是文件夹的话,递归
  45.                         if(f2.isDirectory()){
  46.                                 method(f2,newf);
  47.                         }
  48.                 }
  49.         }

  50.        
  51.        
  52.         public static void copy(File newf, File f2) throws FileNotFoundException,
  53.                         IOException {
  54.                 BufferedInputStream bis =
  55.                                 new BufferedInputStream(new FileInputStream(f2));
  56.                 BufferedOutputStream bos =
  57.                                 new BufferedOutputStream(new FileOutputStream(new File(newf,f2.getName())));
  58.                 int b;
  59.                 while((b=bis.read())!=-1){
  60.                         bos.write(b);
  61.                 }
  62.                
  63.                 bis.close();
  64.                 bos.close();
  65.         }
  66. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马