Question

Is there a way to write data to an OutputStream object which is connected to a channel, and this channel will pass the data to a bytebuffer (preferably, direct bytebuffer)?

I have a situation where a third party function can write its output to an outputStream. I want to be able to write this data to a bytebuffer using channels.

Is it possible?

Thank you

Was it helpful?

Solution

You can easily create a class that extends OutputStream since this only requires one method to be implemented. Sample, untested code:

public final class ByteBufferOutputStream
    extends OutputStream
{
    private final ByteBuffer buf;

    public ByteBufferOutputStream(final int size)
    {
        buf = ByteBuffer.allocateDirect(size);
    }

    @Override
    public void write(final int b)
        throws IOException
    {
        if (buf.remaining() == 0)
            throw new IOException("buffer is full");
        buf.put((byte) (b & 0xff));
    }
}

Then just pass an instance of that class to your API. You'll also probably want to override the other write methods since ByteBuffer has dedicated methods to write byte arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top