Skip to content

ByteBuffer 流

小马哥 edited this page Jun 21, 2016 · 9 revisions

概述

Java NIO 中提供了一个可以进行高效 IO 操作 ByteBuffer 类,但是 ByteBuffer 在使用上有一点不便,就是分配的空间大小是确定的。这就像数组,而不能像 List 一样自动扩容。Java 还提供了可以自动扩容的输入输出字节数组流(ByteArrayInputStream 和 ByteArrayOutputStream),但是它们底层是用数组实现的,而不能直接操作 ByteBuffer。

为了更方便的操作 ByteBuffer,Hprose 提供了基于 ByteBuffer 的输入输出流,可以在 ByteBuffer 上进行流式操作。这部分包括了三个类:

  • ByteBufferStream
  • ByteBufferInputStream
  • ByteBufferOutputStream

其中 ByteBufferStream 类是这部分的核心,它包含了输入输出流的实现。ByteBufferInputStream 是对 ByteBufferStream 的一个 InputSteam 包装。ByteBufferOutputStream 是对 ByteBufferStream 的一个 OutputSteam 包装。

下面重点介绍 ByteBufferStream 类。

ByteBufferStream 类

静态方法

allocate 方法

ByteBufferStream.allocate(capacity);

分配一个容量大小为 capacity 的直接内存的 ByteBuffer 对象。该方法功能 ByteBuffer.allocateDirect 类似,但是它会优先使用 ByteBufferStream 内存池中的已分配的空闲对象作为返回结果。

free 方法

ByteBufferStream.free(buffer);

ByteBuffer 对象放入 ByteBufferStream 内存池,这里的 buffer 应该是在直接内存上分配的 ByteBuffer 对象,并且容量不小于 1024 且为 2 的 n 次方,否则将直接释放。

Clone this wiki locally