Java ByteBuffer search for byte array

Description

Java ByteBuffer search for byte array

import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bb = ByteBuffer.wrap("demo2s.com".getBytes());
    //  w  w  w .  ja  v a  2s. c o m
    System.out.println(Arrays.toString(toArray(bb)));
    bb.flip();
    int index = indexOf(bb, (byte)50);
    System.out.println(index);
  }

  public static int indexOf(ByteBuffer buf, byte value) {
    if (buf.hasArray()) {
        byte[] array = buf.array();
        int begin = buf.arrayOffset() + buf.position();
        int end = buf.arrayOffset() + buf.limit();
        for (int offset = 0; offset < end && offset > -1; ++offset) {
            if (array[begin + offset] == value) {
                return offset;
            }
        }
    } else {
        int begin = buf.position();
        for (int offset = 0; offset < buf.limit(); ++offset) {
            if (buf.get(begin + offset) == value) {
                return offset;
            }
        }
    }
    return -1;
}
  public static byte[] toArray(final ByteBuffer buffer) {
    byte[] array = new byte[buffer.limit()];
    buffer.get(array);
    return array;
  }
}



PreviousNext

Related