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

© Demo_黑马 中级黑马   /  2016-5-23 21:41  /  287 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

File类递归练习(拷贝)
从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
  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. public class Test3 {

  10.         /**
  11.          * 需求:3,从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
  12.          *
  13.          * 把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
  14.          * 分析:
  15.          * 1,在目标文件夹中创建原文件夹
  16.          * 2,获取原文件夹中所有的文件和文件夹,存储在File数组中
  17.          * 3,遍历数组
  18.          * 4,如果是文件就用io流读写
  19.          * 5,如果是文件夹就递归调用
  20.          * @throws IOException
  21.          */
  22.         public static void main(String[] args) throws IOException {
  23.                 File src = Test1.getDir();
  24.                 File dest = Test1.getDir();
  25.                 if(src.equals(dest)) {
  26.                         System.out.println("目标文件夹是源文件夹的子文件夹");
  27.                 }else {
  28.                         copy(src,dest);
  29.                 }
  30.         }
  31.         /*
  32.          * 把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
  33.          * 1,返回值类型void
  34.          * 2,参数列表File src,File dest
  35.          */
  36.         public static void copy(File src, File dest) throws IOException {
  37.                 //1,在目标文件夹中创建原文件夹
  38.                 File newDir = new File(dest, src.getName());
  39.                 newDir.mkdir();
  40.                 //2,获取原文件夹中所有的文件和文件夹,存储在File数组中
  41.                 File[] subFiles = src.listFiles();
  42.                 //3,遍历数组
  43.                 for (File subFile : subFiles) {
  44.                         //4,如果是文件就用io流读写
  45.                         if(subFile.isFile()) {
  46.                                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(subFile));
  47.                                 BufferedOutputStream bos =
  48.                                                 new BufferedOutputStream(new FileOutputStream(new File(newDir,subFile.getName())));
  49.                                
  50.                                 int b;
  51.                                 while((b = bis.read()) != -1) {
  52.                                         bos.write(b);
  53.                                 }
  54.                                
  55.                                 bis.close();
  56.                                 bos.close();
  57.                         //5,如果是文件夹就递归调用
  58.                         }else {
  59.                                 copy(subFile,newDir);
  60.                         }
  61.                 }
  62.         }
  63. }
复制代码



0 个回复

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