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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Fate_stay 中级黑马   /  2016-9-19 22:17  /  1075 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOError;
import java.io.IOException;
/*
* 复制 多级文件夹     
* 文件夹 下还有文件夹 .  
* 把 bbb 复制到  eee下  
*
* 递归调用  复制文件夹的方法  
*
* copy(src , dest )
*/
public class Test2 {
        public static void main(String[] args) throws IOException {

                // 创建文件夹 对象
                File src = new File("bbb");
                File dest = new File("eee\\bbb");
                copy(src, dest);
        }

        /*
         * 1.创建文件夹 : 复制多级的文件夹, 那么就需要在方法中,创建多级文件夹 2.当你要复制文件夹, 本身自己就是复制文件夹的功能,那么此时
         * 调用自己即可.
         */
        public static void copy(File src, File dest) throws IOException {
                // 创建目标文件夹
                if (!dest.exists()) {
                        dest.mkdirs();
                }

                // 遍历src 文件夹
                File[] listFiles = src.listFiles();

                for (File file : listFiles) {
                        if (file.isFile()) {
                                // 读取源文件 file : bbb下的文件 bj.txt
                                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                                // 写出 文件 dest :eee\bbb\bj.txt
                                BufferedOutputStream bos = new BufferedOutputStream(
                                                new FileOutputStream(new File(dest, file.getName())));

                                int b;
                                while ((b = bis.read()) != -1) {
                                        bos.write(b);
                                }
                                bos.close();
                                bis.close();
                        } else {
                                 copy(file, new File(dest, file.getName()));
                        }
                }

        }
}


0 个回复

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