Sometime, your program may need to read data from a ByteBuffer
buffer into a InputStream
object. There is no class in Java library that provide the facility to do the conversion.
Anyway, to use a ByteBuffer
object as an InputStream
is pretty simple. What you need to do is to write a class wrapper that inherit InputStream
and override the read()
function in InputStream.
Here is the example:
public class ByteBufferInputStream extends InputStream { private int bbisInitPos; private int bbisLimit; private ByteBuffer bbisBuffer; public ByteBufferInputStream(ByteBuffer buffer) { this(buffer, buffer.limit() - buffer.position()); } public ByteBufferInputStream(ByteBuffer buffer, int limit) { bbisBuffer = buffer; bbisLimit = limit; bbisInitPos = bbisBuffer.position(); } @Override public int read() throws IOException { if (bbisBuffer.position() - bbisInitPos > bbisLimit) return -1; return bbisBuffer.get(); } }
In this class, ByteBufferInputStream
, you can specify the limit to read from the ByteBuffer
so that you can use the data in ByteBuffer later for other purposes. The read behavior is same as other InputStream
class, where when there is no more data to read (or reached the preset limit), the read()
function returns negative one.
Leave a Reply