首页 > 解决方案 > Remove some bytes from byte buffer and returning same byte buffer

问题描述

I have a byte buffer from which i need to remove some bytes of carriage return /r and return the same byte buffer after removal. With help i was able to remove the the /r using stream as below but that return a int[], is there any way where i do not need to create another byte buffer and use the same one after removing the /r? Below is the code i used

IntStream.range(bb.position(), bb.limit())
          .filter(i -> bb.get(i) != 13)
          .map(i -> bb.get(i)) 
          .toArray();

Let me know any other way to do this?

标签: javabytebytebuffercarriage-return

解决方案


你可以使用这个辅助方法:

public static int removeAll(ByteBuffer buf, int b) {
    int removed = 0;
    for (int i = 0, start = 0, cap = buf.capacity(); i < cap; i++) {
        byte read = buf.get(i);
        buf.put(i, (byte) 0);
        if (read != b) {
            buf.put(start++, read);
        } else {
            removed++;
        }
    }
    return removed;
}

然后你可以这样调用:

removeAll(buf, '\r');

它只是迭代缓冲区,并删除与提供的参数相等的字节,留0在缓冲区的末尾以解释丢失的元素。


推荐阅读