Does this byte array begin with match array content? - Java java.lang

Java examples for java.lang:byte Array

Description

Does this byte array begin with match array content?

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] source = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        byte[] match = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(startsWith(source, match));
    }/*  w w w  . j  av a  2  s . c o  m*/

    /**
     * Does this byte array begin with match array content?
     * @param source Byte array to examine
     * @param match Byte array to locate in <code>source</code>
     * @return true If the starting bytes are equal
     */
    public static boolean startsWith(byte[] source, byte[] match) {
        return startsWith(source, 0, match);
    }

    /**
     * Does this byte array begin with match array content?
     * @param source Byte array to examine
     * @param offset An offset into the <code>source</code> array
     * @param match Byte array to locate in <code>source</code>
     * @return true If the starting bytes are equal
     */
    public static boolean startsWith(byte[] source, int offset, byte[] match) {
        if (match.length > (source.length - offset)) {
            return false;
        }
        for (int i = 0; i < match.length; i++) {
            if (source[offset + i] != match[i]) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials