[英]Finding the positions of a particular byte in byte buffer
我有一個字節緩沖區,我需要從中找到字符“/ n”在該緩沖區中的位置。 該字節緩沖區中可能存在許多“/ n” ,我需要找到所有這些位置。 有什么方法我不需要轉換為字節數組並使用 Java 8 對其進行循環?
ByteBuffer
class 提供絕對獲取操作,可以訪問任何有效索引處的值。 例如, ByteBuffer#get(int)
接受一個索引並返回該索引處的字節。 它在不改變緩沖區的 position 的情況下執行此操作,這意味着您的代碼不會有任何副作用。 這是一個查找單個字節的所有索引的示例:
public static int[] allIndicesOf(ByteBuffer buf, byte b) {
return IntStream.range(buf.position(), buf.limit())
.filter(i -> buf.get(i) == b)
.toArray();
}
這避免了將信息復制到byte[]
中,並將ByteBuffer
留在與該方法相同的 state 中。 另請注意,緩沖區僅從其當前position搜索到其限制。 如果要搜索整個緩沖區,請使用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();
}
該代碼適用於獲取 position。 如果我只想在從該字節緩沖區的字節緩沖區中找到該 ASCII 字符“10”時刪除它,是否有可能?
下面是刪除所有出現的指定字節的示例:
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.