“零拷贝”数据传输

Java NIO中的transferTo方法等

1、public abstract long transferTo(long position, long count, WritableByteChannel target) throws IOException;//此为FileChannel类的方法

        该方法读取通道对象(调用者,即FileChannel对象)所在文件的中的给定位置(position)处开始的count个字节到目标通道(target)中。

2、public void transferToFully(fileChannel filech,long position, int count ) throws IOException;//此为SocketOutPutStream类的方法

      该方法将通道文件filech中的position处开始的count个字节发送到SocketOutPutStream对象中。

例:

  1. /**  
  2.      * 复制文件(以超快的速度复制文件)  
  3.      *   
  4.      * @param srcFile  
  5.      *            源文件File  
  6.      * @param destDir  
  7.      *            目标目录File  
  8.      * @param newFileName  
  9.      *            新文件名  
  10.      * @return 实际复制的字节数,如果文件、目录不存在、文件为null或者发生IO异常,返回-1  
  11.      */  
  12.     public static long copyFile2(File srcFile, File destDir, String newFileName) {   
  13.         long copySizes = 0;   
  14.         if (!srcFile.exists()) {   
  15.             System.out.println("源文件不存在");   
  16.             copySizes = -1;   
  17.         } else if (!destDir.exists()) {   
  18.             System.out.println("目标目录不存在");   
  19.             copySizes = -1;   
  20.         } else if (newFileName == null) {   
  21.             System.out.println("文件名为null");   
  22.             copySizes = -1;   
  23.         } else {   
  24.             try {   
  25.                 FileChannel fcin = new FileInputStream(srcFile).getChannel();   
  26.                 FileChannel fcout = new FileOutputStream(new File(destDir,   
  27.                         newFileName)).getChannel();   
  28.                 long size = fcin.size();   
  29.                 fcin.transferTo(0, fcin.size(), fcout);   
  30.                 fcin.close();   
  31.                 fcout.close();   
  32.                 copySizes = size;   
  33.             } catch (FileNotFoundException e) {   
  34.                 e.printStackTrace();   
  35.             } catch (IOException e) {   
  36.                 e.printStackTrace();   
  37.             }   
  38.         }   
  39.         return copySizes;   
  40.     }  

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值