Growing ByteBuffer

前端 未结 11 1115
温柔的废话
温柔的废话 2021-01-31 14:21

Has anyone has ever seen an implementation of java.nio.ByteBuffer that will grow dynamically if a putX() call overruns the capacity?

The reason I want to do it this way

11条回答
  •  情歌与酒
    2021-01-31 15:11

    A ByteBuffer cannot really work this way, as its design concept is to be just a view of a specific array, which you may also have a direct reference to. It could not try to swap that array for a larger array without weirdness happening.

    What you want to use is a DataOutput. The most convenient way is to use the (pre-release) Guava library:

    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.write(someBytes);
    out.writeInt(someInt);
    // ...
    return out.toByteArray();
    

    But you could also create a DataOutputStream from a ByteArrayOutputStream manually, and just deal with the spurious IOExceptions by chaining them into AssertionErrors.

提交回复
热议问题