使用FileChannel复制文件

来源:互联网 发布:echart动态获取数据 编辑:程序博客网 时间:2024/05/17 23:28

方法1:

 

public void copyFile(File src, File dest) {
     FileChannel in = null;
     FileChannel out = null;
     try {
      FileInputStream fis = new FileInputStream(src);
         FileOutputStream fos = new FileOutputStream(dest);
         in = fis.getChannel();
         out = fos.getChannel();
         
         ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
         while (true) {
          int size = in.read(buf);
          if (size == -1) {
           break;
          }
          buf.flip();
          out.write(buf);
         }
         
     } catch (Exception e) {
      e.printStackTrace();
     } finally {
      if (in != null) try {in.close();} catch(Exception e) {}
      if (out != null) try {out.close();} catch(Exception e) {}
     }
    }

 

 

方法2:

 

 public void copyFile2(File src, File dest) {
  FileChannel sfc = null;
  FileChannel dfc = null;
  try {
   FileInputStream fis = new FileInputStream(src);
   FileOutputStream fos = new FileOutputStream(dest);
   sfc = fis.getChannel();
   dfc = fos.getChannel();
   
   sfc.transferTo(0, sfc.size(), dfc);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (sfc != null) {
    try {
     sfc.close();
    } catch (IOException e) {
    }
   }
   if (dfc != null) {
    try {
     dfc.close();
    } catch (Exception e) {
     
    }
   }
  }
 }

原创粉丝点击