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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘德坤 中级黑马   /  2015-10-10 09:50  /  456 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.itheima;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test22 {

        /**
         * 代码实现c盘某个文件夹复制到D盘中,加上代码,加上注释,加上思路。
         */
        public static void main(String[] args) throws IOException {
                File orig=new File("D:\\Test");
                File dest=new File("E:\\Test2");
                copy(orig,dest);      
        }
        public static void copy(File orig,File dest) throws IOException{
                if (!orig.exists()) {
                        System.out.println("原文件不存在");
                        return ;
                }
                if (!dest.exists()||!dest.isDirectory()) {
                        dest.mkdirs();//创建多级目录要用mkdirs().
                }
                File f = new File(dest.getPath()+"\\"+orig.getName());//在目的目录下创建一个与待复制文件夹同名的目录。
                f.mkdir();
                                
                File[] files = orig.listFiles();
                for (File file : files) {
                        if (file.isDirectory()) {                       
                                copy(file,f);
                        }else {
                                BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
                                                                //获取路径的字符串形式用getPath();
                                BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(f.getPath()+"\\"+file.getName()));
                                int b=0;
                                while ((b=bis.read()) !=-1) {
                                        bos.write(b);
                                }
                                bis.close();
                                bos.close();
                                System.out.println(file.getName()+"拷贝完成");
                        }
                }
        }

}

1 个回复

倒序浏览
谢谢,学习了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马