io流的综合使用

微笑、不失礼 提交于 2019-11-30 05:47:25
//第一步:给定指定原路径和目标路径

 public static void main(String[] args) throws IOException {
     //源目录
     File src = new File("d:\\源目录");
     if(src.isDirectory()==false){
         System.out.println("源文件路径不存在");
         return;
     }
     //当目标目录不存在的时候,创建
     File dest = new File("e:\\g");
     isExit(dest);
     copyDir(src,dest);

 }


//第二步:开始递归复制

 public static void copyDir(File src,File dest) throws IOException {
     //为了严谨起见,我们首先对源目录和目标目录进行判断,看他们到底是不是目录
     if(src.isDirectory() && dest.isDirectory()) {
         //desc表示在目的地路径下
         //src.getName源路径的名称(创建文件夹)
         File newDir = new File(dest , src.getName());
         if(!newDir.exists()) {
             newDir.mkdir();
         }
         //获取源目录下所有的文件和子目录
         File[] files = src.listFiles();
         for (File file : files) {
             //如果是文件就使用字节流进行复制
             if(file.isFile()) {
                 //创建输入流对象
                 FileInputStream fis = new FileInputStream(file);
                 //创建输出流对象
                 // "d:\\a\\myAPI" + "classpath" = d:\\a\\myAPI\\classpath
                 FileOutputStream fos = new FileOutputStream(new File(newDir,file.getName()));

                 byte[] bys = new byte[1024];
                 int len;
                 while((len = fis.read(bys)) != -1) {
                     fos.write(bys, 0, len);
                 }
                 fis.close();
                 fos.close();
             }
             //如果是文件夹就进行这个方法
             else if(file.isDirectory()) {
                 copyDir(file,newDir);
             }
         }
     }
 }
 /**
  * 当目标目录不存在的时候,创建
  */
 private static void isExit(File file){
     if(!file.exists()){
         try {
             file.mkdirs();
         } catch (Exception e) {
             e.printStackTrace();
             System.out.println("创建文件夹错误");
         }
     }
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!