码迷,mamicode.com
首页 > 其他好文 > 详细

复制一个文件夹下所有的文件和子文件夹内容到另一个文件夹

时间:2016-05-13 05:24:59      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:java   文件   文件夹   

PS:涉及单个文件复制、目录的创建、递归的使用

public class CopyAllFiles {
 public static void main(String[] args) {
  copyDirectory("F:\\XXX", "F:\\YYY");
 }
 
 //复制文件的方法
 public static void copyFiles(File sourceFile, File targetFile) {
  //声明
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;
  //创建字节数组
  byte[] bs = new byte[1024 * 5];
  
  try {
   //创建对象
   bis = new BufferedInputStream(new FileInputStream(sourceFile));
   bos = new BufferedOutputStream(new FileOutputStream(targetFile));
   //读取
   int x = bis.read(bs);
   //判断
   while(x > 0) {
    //存盘
    bos.write(bs, 0, x);
    //再次读取
    x = bis.read(bs);
   }
   bos.flush();//刷新
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally {
   //关闭流
   if(bis != null) {
    try {
     bis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if(bos != null) {
    try {
     bos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  
 }
 
 //复制目录的方法
 public static void copyDirectory( String sourceDirectory, String targetDirectory) {
  //创建文件对象
  File sourceFile = new File(sourceDirectory);
  File targetFile = new File(targetDirectory);
  //判断源目录
  if(!sourceFile.exists() || !sourceFile.isDirectory()) {
   System.out.println("源目录不存在!!");
   return ;
  }
  
  //判断目标目录,若不存在,则手动创建
  if(!targetFile.exists()) {
   targetFile.mkdirs();
  }
  
  //获取源目录的所有文件和目录
  File[] sourceList = sourceFile.listFiles();
  //遍历源目录
  for (int i = 0; i < sourceList.length; i++) {
   //若为文件
   if(sourceList[i].isFile()) {
    //源文件
    File sourceF = sourceList[i];
    //目标文件
    File targetF = new File(targetFile,sourceList[i].getName());
    //调用复制文件的方法
    copyFiles(sourceF, targetF);
   }
   //若为目录
   if(sourceList[i].isDirectory()) {
    //源目录
    String sourceD = sourceDirectory + File.separator + sourceList[i].getName();
    //目标目录
    String targetD = targetDirectory + File.separator + sourceList[i].getName();
    //递归调用复制目录的方法
    copyDirectory(sourceD, targetD);
   }
  }
 }
}

 

本文出自 “顺其自然” 博客,请务必保留此出处http://wangchuankun.blog.51cto.com/6023368/1772475

复制一个文件夹下所有的文件和子文件夹内容到另一个文件夹

标签:java   文件   文件夹   

原文地址:http://wangchuankun.blog.51cto.com/6023368/1772475

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!