代码之家  ›  专栏  ›  技术社区  ›  Justin

ByteBuffer可以实现数据输出/数据输入吗?

  •  10
  • Justin  · 技术社区  · 14 年前

    有什么微妙的原因 java.nio.ByteBuffer java.io.DataOutput java.io.DataInput ,还是作者不选择这样做?映射调用似乎很简单(例如putInt()->writeInt())。

    others ,显然)have是较老的类,它们知道如何使用通用接口(DataInput/DataOutput)序列化/序列化自己。我想重用我的自定义序列化,而不必为ByteBuffer编写自定义代理。

    2 回复  |  直到 13 年前
        1
  •  4
  •   Andrejs    11 年前

    把缓冲器包起来 ByteArrayInputStream ByteArrayOutputStream 使用 put() wrap() 方法。有一个 ByteBuffer 直接模拟数据输入/输出流与事先不知道大小有关。如果有超支怎么办?

    ByteBufferOutputStream 其中,您可以包装/公开所需的行为。存在这样的例子; Apache avro

    ByteArrayOutputStream backing = new ByteArrayOutputStream();
    DataOutput foo = new DataOutputStream(backing); 
    // do your serialization out to foo
    
    foo.close();
    ByteBuffer buffer = ByteBuffer.wrap(backing.toByteArray());
    // now you've got a bytebuffer...
    
        2
  •  4
  •   jbellis    13 年前

    使用直接缓冲区的更好方法是:

    class ByteBufferOutputStream extends OutputStream
    {
        private final ByteBuffer buffer;
    
        public ByteBufferOutputStream(ByteBuffer buffer)
        {
            this.buffer = buffer;
        }
    
        public void write(int b) throws IOException
        {
            buffer.put((byte) b);
        }
    }
    

    请注意,这需要在完成对buffer.flip()的写入之后,才能读取它。