在字节缓冲区中查找特定字节的位置

Finding the positions of a particular byte in byte buffer

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

ByteBuffer class 提供绝对 get 操作,可以访问任何有效索引处的值。例如,ByteBuffer#get(int) 接受一个索引和 returns 该索引处的字节。它在不改变缓冲区位置的情况下执行此操作,这意味着您的代码不会有任何副作用。这是一个查找单个字节的所有索引的示例:

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

这避免了将信息复制到 byte[] 中,并使 ByteBuffer 处于与提供给方法时相同的状态。另请注意,仅从其当前 position 到其 limit 搜索缓冲区。如果要搜索整个缓冲区,请使用 range(0, buf.capacity()).

这是另一个示例,但这个示例允许您在缓冲区中搜索“子数组”:

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();
}

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?

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

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);
    }
  }
}