将文件流组装到hessianOutPut里,远程上传文件使用

将文件流组装到hessianOutPut里,远程上传文件使用
  1. private static void uploadNIO(File file, HessianOutput out)  
  2.             throws IOException {  
  3.         out.writeByteBufferStart();  
  4.         System.out.println("file = " + file.exists());  
  5.         try {  
  6.             FileChannel channel = new FileInputStream(file).getChannel();  
  7.             System.out.println("file Size: " + channel.size());  
  8.             final int size = 10485760;// 10485760=1024*1024*10  
  9.             ByteBuffer buf = ByteBuffer.allocateDirect(size);  
  10.             int numRead = 0;  
  11.             do {  
  12.                 numRead = channel.read(buf);  
  13.                 buf.flip();//limit=current position;position=0;  
  14.                 int limit = buf.limit();  
  15.                 byte[] tmpByteArray = new byte[limit];  
  16.                 while (buf.hasRemaining()) {  
  17.                     buf.get(tmpByteArray);  
  18.                     out.writeByteBufferPart(tmpByteArray, 0, limit);  
  19.                 }  
  20.                 buf.clear();//position=0;limit=capacity;reset mark;  
  21.             } while (numRead > 0);  
  22.             out.writeByteBufferEnd(new byte[0], 00);  
  23.         } catch (Error e) {  
  24.             e.printStackTrace();  
  25.             throw new RuntimeException(e);  
  26.         }  
  27.     } 


Buffer要点:
  • capacity(): buffer的最大容量
  • limit(): 已用的buffer量
  • position(): 当前定位下一个读/写的位置
  • mark(): 最后一次用reset()重置的位置
  • 常用方法:
     方法名 说明
     position() 返回当前位置
     position(int index) 将index设为当前位置
     limit() 返回当前限度
     limit(int newLimit) 将newLimit设为当前限度
     clear() position设0,limit设capacity,取消所有mark
     rewind() position设0,取消所有mark
     flip() limit设为当前position,position设为0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值