在字节缓冲区中查找特定字节的位置 [英] Finding the positions of a particular byte in byte buffer

查看:106
本文介绍了在字节缓冲区中查找特定字节的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节缓冲区,我需要从该字节缓冲区中找到字符'/n'的位置.该字节缓冲区中可能存在许多'/n',我需要找到所有这些位置.有什么方法不需要使用Java 8转换为字节数组并在其上循环?

I have a byte buffer from which i need to find the positions of character '/n' in that buffer. There may be many '/n' present in that byte buffer and i need to find all those positions. Is there any way in which i did not need to convert into byte array and loop over it using Java 8?

推荐答案

ByteBuffer 类提供了绝对的 get 操作,可以在任何有效索引处访问该值.例如,

The ByteBuffer class offers absolute get operations which can access the value at any valid index. For instance, ByteBuffer#get(int) accepts an index and returns the byte at that index. It does this without mutating the position of the buffer, meaning your code won't have any side-effects. Here's an example which finds all indices of a single byte:

public static int[] allIndicesOf(ByteBuffer buf, byte b) {
  return IntStream.range(buf.position(), buf.limit())
      .filter(i -> buf.get(i) == b)
      .toArray();
}

这样可以避免将信息复制到 byte [] 中,并使 ByteBuffer 保持与方法相同的状态.还要注意,缓冲区仅从其当前位置到其 limit 进行搜索.如果要搜索整个缓冲区,请使用 range(0,buf.capacity()).

This avoids copying the information into a byte[] and leaves the ByteBuffer in the same state as it was when given to the method. Also note that the buffer is only searched from its current position to its limit. If you want to search the entire buffer then use range(0, buf.capacity()).

这里是另一个例子,除了这个例子,您可以搜索"sub-array"子对象.在缓冲区中:

Here's another example except this one allows you to search for a "sub-array" in the buffer:

public static int[] allIndicesOf(ByteBuffer buf, byte[] b) {
  if (b.length == 0) {
    return new int[0];
  }
  return IntStream.rangeClosed(buf.position(), buf.limit() - b.length)
      .filter(i -> IntStream.range(0, b.length).allMatch(j -> buf.get(i + j) == b[j]))
      .toArray();
}


该代码可用于获取职位.如果我只是想从该字节缓冲区的字节缓冲区中删除该ASCII字符'10',是否有可能?

The code works for getting the position. Is it possible if i just want to delete that ASCII char '10' when found in bytebuffer fro that byte buffer?

下面是删除所有出现的指定字节的示例:

Here's an example of removing all occurrences of the specified byte:

public static void removeAll(ByteBuffer buf, byte b) {
  for (int i = buf.position(); i < buf.limit(); i++) {
    // find first occurrence
    if (buf.get(i) == b) {
      // copy every remaining byte which != 'b' over
      for (int j = i + 1; j < buf.limit(); j++) {
        if (buf.get(j) != b) {
          buf.put(i++, buf.get(j));
        }
      }
      // update limit of buffer (implicitly causes outer for loop to exit)
      buf.limit(i);
    }
  }
}

这篇关于在字节缓冲区中查找特定字节的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆