Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012-2015 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/

import java.io.ByteArrayOutputStream;

public class Main {
    public static byte[] replaceAll(byte[] src, byte[] target, byte[] replacement) {
        final ByteArrayOutputStream result = new ByteArrayOutputStream(src.length);
        int i = 0;
        int wrote = 0;
        while ((i = indexOf(src, target, i)) != -1) {
            int len = i - wrote;
            result.write(src, wrote, len);
            result.write(replacement, 0, replacement.length);
            wrote += len + target.length;
            i += target.length;
        }
        result.write(src, wrote, src.length - wrote);
        return result.toByteArray();
    }

    /**
     * Searches for target bytes in the source bytes.
     *
     * @param src
     *         where to search
     * @param target
     *         what to search
     * @param fromIdx
     *         source index to search from
     * @return index of the first occurrence or -1 if nothing was found
     */
    public static int indexOf(byte[] src, byte[] target, int fromIdx) {
        final int to = src.length - target.length + 1;
        for (int i = fromIdx; i < to; i++) {
            if (src[i] == target[0]) {
                boolean equals = true;
                for (int j = 1, k = i + 1; j < target.length && equals; j++, k++) {
                    if (src[k] != target[j]) {
                        equals = false;
                    }
                }
                if (equals) {
                    return i;
                }
            }
        }
        return -1;
    }
}