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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

/*4.请编写程序,复制多层文件夹,并测试
答案:*/
public class CopyDirectorys {
        public static void main(String[] args) throws Exception {
                //1:封装数据源
                File srcPath = new File("D:\\java\\wokepace\\1day24\\b");
                //2:封装目的地
                File destPath = new File("D:\\java\\wokepace\\1day24\\b-copy");
                //复制文件夹
                copyDirectory(srcPath, destPath);
                System.out.println("复制完毕!");
        }
        //复制文件夹
        private static void copyDirectory(File srcPath, File destPath) throws Exception {
                //3:创建目的地文件夹
                destPath.mkdir();
                //4:获取数据源中 所有的File对象
                File[] files = srcPath.listFiles();
                //5:遍历,获取到每一个File对象
                for (File file : files) {
                        //6:判断File对象是否为文件夹
                        if (file.isDirectory()) {
                                //是: 递归 回到步骤3
                                //file -- E:\resource\各种专治
                                //dest -- YesDirectory\各种专治
                                File dest = new File(destPath, file.getName());
                                copyDirectory(file, dest);
                        } else {
                                //否:复制文件
                                //file -- E:\resource\Demo.java
                                //dest -- YesDirectory\Demo.java
                                File dest = new File(destPath, file.getName());
                                //复制文件
                                copyFile(file, dest);
                        }
                }
        }
       
        //复制文件
        private static void copyFile(File srcPath, File destPath) throws Exception {
                //数据源
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
                //目的地
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
                //读
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len=bis.read(buffer)) != -1) {
                        //写
                        bos.write(buffer, 0, len);       
                }
                //释放资源
                bis.close();
                bos.close();
        }
}


1 个回复

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