Searching for a sequence of Bytes in a Binary File with Java

Viewed 26450

I have a sequence of bytes that I have to search for in a set of Binary files using Java.

Example: I'm searching for the byte sequence DEADBEEF (in hex) in a Binary file. How would I go about doing this in Java? Is there a built-in method, like String.contains() for Binary files?

4 Answers
private int bytesIndexOf(byte[] source, byte[] search, int fromIndex) {
    boolean find = false;
    int i;
    for (i = fromIndex; i < (source.length - search.length); i++) {
        if (source[i] == search[0]) {
            find = true;
            for (int j = 0; j < search.length; j++) {
                if (source[i + j] != search[j]) {
                    find = false;
                }
            }
        }
        if (find) {
            break;
        }
    }
    if (!find) {
        return -1;
    }
    return i;
}
Related