Netty java getting data from ByteBuf

后端 未结 1 394
南方客
南方客 2020-12-24 06:56

How to get a byte array from ByteBuf efficiently in the code below? I need to get the array and then serialize it.

package testingNetty;
import          


        
相关标签:
1条回答
  • 2020-12-24 07:11
    ByteBuf buf = ...
    byte[] bytes = new byte[buf.readableBytes()];
    buf.readBytes(bytes);
    

    If you don't want the readerIndex to change:

    ByteBuf buf = ...
    byte[] bytes = new byte[buf.readableBytes()];
    int readerIndex = buf.readerIndex();
    buf.getBytes(readerIndex, bytes);
    

    If you want to minimize the memory copy, you can use the backing array of the ByteBuf, if it's available:

    ByteBuf buf = ...
    byte[] bytes;
    int offset;
    int length = buf.readableBytes();
    
    if (buf.hasArray()) {
        bytes = buf.array();
        offset = buf.arrayOffset();
    } else {
        bytes = new byte[length];
        buf.getBytes(buf.readerIndex(), bytes);
        offset = 0;
    }
    

    Please note that you can't simply use buf.array(), because:

    • Not all ByteBufs have backing array. Some are off-heap buffers (i.e. direct memory)
    • Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the following isn't necessarily true because the buffer might be a slice of other buffer or a pooled buffer:
      • buf.array()[0] == buf.getByte(0)
      • buf.array().length == buf.capacity()
    0 讨论(0)
提交回复
热议问题