java - 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?
解决方案
你可以使用这个辅助方法:
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
在缓冲区的末尾以解释丢失的元素。
推荐阅读
- c - 将结构内的整数类型数组初始化为 NULL 是否可以/有效?
- python - 如何将一天中的分钟附加到 Python 中的列表中?
- mysql - mysql复制错误:截断不正确的DOUBLE值
- apache-spark - 使用 Spark SQL 查询的 CLUSTER BY
- java - 设计会话过期服务
- django - 与 values_list 一起使用时迭代器是否提供改进?
- c - 尽管 C 严格的别名规则,为什么允许引用具有相似第一成员的结构?
- python-3.x - python程序输出尾随零..如何获得零输出
- reactjs - 在桌子上反应引导手风琴
- azure-devops - Azure DevOps 中的 GetUsers