---
title: "将文件流组装到hessianOutPut里,远程上传文件使用"
author: "weishuwei"
date: "2007-06-20T16:56:27Z"
tags: []
slug: "hessianoutput"
draft: false
lastmod: "2007-06-20T16:56:27Z"
id: 92449
url: "https://weishuwei.iteye.com/blog/92449"
---

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

01. private static void uploadNIO(File file, HessianOutput out)
02. throws IOException {
03. out.writeByteBufferStart();
04. System.out.println("file = " + file.exists());
05. try {
06. FileChannel channel = new FileInputStream(file).getChannel();
07. System.out.println("file Size: " + channel.size());
08. final int size = 10485760;// 10485760=1024\*1024\*10
09. 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 &gt; 0);
22. out.writeByteBufferEnd(new byte\[0], 0, 0);
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