Growing ByteBuffer

前端 未结 11 1142
温柔的废话
温柔的废话 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:07

    Another solution for this would be to allocate more than enough memory, fill the ByteBuffer and then only return the occupied byte array:

    Initialize a big ByteBuffer:

    ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
    

    After you're done putting things into it:

    private static byte[] getOccupiedArray(ByteBuffer byteBuffer)
    {
        int position = byteBuffer.position();
        return Arrays.copyOfRange(byteBuffer.array(), 0, position);
    }
    

    However, using a org.apache.commons.io.output.ByteArrayOutputStream from the start would probably be the best solution.

提交回复
热议问题