Copy first "count" bytes from byte array. - Java java.lang

Java examples for java.lang:byte Array

Description

Copy first "count" bytes from byte array.

Demo Code

/*/*w  w  w .j  a va  2 s  .  c  om*/
 This file is part of p300.


 p300 is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 p300 is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with p300.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int count = 2;
        System.out.println(java.util.Arrays.toString(copy(b, count)));
    }

    /**
     * Copy first "count" bytes from byte array.
     * Won't change the original array.
     * @param b
     * @param count
     * @return Copy of the first "count" bytes
     */
    public static byte[] copy(byte[] b, int count) {
        int copy = 0;
        if (b != null) {
            copy = Math.min(b.length, count);
        }
        byte[] result = new byte[copy];
        for (int i = 0; i < copy; i++) {
            result[i] = b[i];
        }

        return result;
    }
}

Related Tutorials