文件/文件夹复制


 /**
  * 通道对通道复制效率高
  * @param f1
  *            源文件
  * @param f2
  *            目的文件
  * @return
  * @throws Exception
  */
 public static long forChannel(File f1, File f2) throws Exception {
  long time = new Date().getTime();
  int length = 2097152;
//每次以2m速度传输
  FileInputStream in = new FileInputStream(f1);
  FileOutputStream out = new FileOutputStream(f2);

// 创建输入,输出通道
  FileChannel inC = in.getChannel();
  FileChannel outC = out.getChannel();
  ByteBuffer b = null;
  while (true) {
   if (inC.position() == inC.size()) {
    inC.close();
    outC.close();
    return new Date().getTime() - time;
   }
   if ((inC.size() - inC.position()) < length) {
    length = (int) (inC.size() - inC.position());
   } else
    length = 2097152;
   b = ByteBuffer.allocateDirect(length);
   inC.read(b);
   b.flip();
   outC.write(b);
   outC.force(false);
  }
 }

 

 


 /*
  * 复制整个文件夹内容
  *
  * @param oldPath String 原文件路径 如:c:/old (注意参数的路径格式
  *
  * @param newPath String 复制后路径 如:f:/new
  *
  * @return boolean
  */
 private static void copyFolder(String oldPath, String newPath) {

  try {
   (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
   File a = new File(oldPath);
   String[] file = a.list();
   File temp = null;
   // 复制文件夹
   if (file != null) {
    for (int i = 0; i < file.length; i++) {
     if (oldPath.endsWith(File.separator)) {
      temp = new File(oldPath + file[i]);
     } else {
      temp = new File(oldPath + File.separator + file[i]);
     }
     // 处理文件
     if (temp.isFile()) {
      FileInputStream input = new FileInputStream(temp);
      FileOutputStream output = new FileOutputStream(newPath
        + "/" + (temp.getName()).toString());

      byte[] b = new byte[1024 * 5];
      int len;
      while ((len = input.read(b)) != -1) {
       output.write(b, 0, len);
      }
      output.flush();
      output.close();
      input.close();

     }

     if (temp.isDirectory()) {// 如果是子文件夹 ,使用递归
      copyFolder(oldPath + "/" + file[i], newPath + "/"
        + file[i]);
     }
    }
   }
   else{
    String orgFileName = oldPath.substring(oldPath.lastIndexOf("/"),oldPath.length());
    System.out.println(orgFileName );
    // 复制单个文件
      forChannel(new File(oldPath),new File(newPath+ "/"+orgFileName));
   }
  } catch (Exception e) {
   System.out.println("复制整个文件夹内容操作出错");
   e.printStackTrace();
  }
 }

 

 

发散:通过这样复制方式去实现文件上传,应该没有问题吧?!

前提是上传到应用服务器上而不是web服务器上

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值