2

有没有办法将数据写入连接到通道的 OutputStream 对象,并且该通道会将数据传递给字节缓冲区(最好是直接字节缓冲区)?

我有一种情况,第三方函数可以将其输出写入 outputStream。我希望能够使用通道将此数据写入字节缓冲区。

是否可以?

谢谢

4

1 回答 1

1

您可以轻松地创建一个类,extends OutputStream因为这只需要实现一个方法。示例,未经测试的代码:

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));
    }
}

然后只需将该类的一个实例传递给您的 API。您可能还想覆盖其他write方法,因为ByteBuffer有专门的方法来写入字节数组。

于 2014-02-27T10:55:48.037 回答