将文件流组装到hessianOutPut里,远程上传文件使用
- private static void uploadNIO(File file, HessianOutput out)
- throws IOException {
- out.writeByteBufferStart();
- System.out.println("file = " + file.exists());
- try {
- FileChannel channel = new FileInputStream(file).getChannel();
- System.out.println("file Size: " + channel.size());
- final int size = 10485760;// 10485760=1024*1024*10
- ByteBuffer buf = ByteBuffer.allocateDirect(size);
- int numRead = 0;
- do {
- numRead = channel.read(buf);
- buf.flip();//limit=current position;position=0;
- int limit = buf.limit();
- byte[] tmpByteArray = new byte[limit];
- while (buf.hasRemaining()) {
- buf.get(tmpByteArray);
- out.writeByteBufferPart(tmpByteArray, 0, limit);
- }
- buf.clear();//position=0;limit=capacity;reset mark;
- } while (numRead > 0);
- out.writeByteBufferEnd(new byte[0], 0, 0);
- } catch (Error e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
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
本文介绍了一种利用Hessian框架进行远程文件上传的方法。通过FileChannel和ByteBuffer实现了文件流的有效传输,确保了文件能够被正确地分割并发送至远程服务器。
937

被折叠的 条评论
为什么被折叠?



