transferring bytes from one ByteBuffer to another

前端 未结 3 1036
无人及你
无人及你 2021-01-02 23:41

What\'s the most efficient way to put as many bytes as possible from a ByteBuffer bbuf_src into another ByteBuffer bbuf_dest (as well as know how m

3条回答
  •  醉话见心
    2021-01-03 00:35

    As you've discovered, getting the backing array doesn't always work (it fails for read only buffers, direct buffers, and memory mapped file buffers). The better alternative is to duplicate your source buffer and set a new limit for the amount of data you want to transfer:

    int maxTransfer = Math.min(bbuf_dest.remaining(), bbuf_src.remaining());
    // use a duplicated buffer so we don't disrupt the limit of the original buffer
    ByteBuffer bbuf_tmp = bbuf_src.duplicate ();
    bbuf_tmp.limit (bbuf_tmp.position() + maxTransfer);
    bbuf_dest.put (bbuf_tmp);
    
    // now discard the data we've copied from the original source (optional)
    bbuf_src.position(bbuf_src.position() + maxTransfer);
    

提交回复
热议问题