Java Random Byte Array randomByteArray(int length)

Here you can find the source of randomByteArray(int length)

Description

Create an array of random bytes

License

Open Source License

Parameter

Parameter Description
length The length of the created array

Return

the byte array

Declaration

public static byte[] randomByteArray(int length) 

Method Source Code

//package com.java2s;
/*/*from  w w w  .java2s .co m*/
 *
 *  * Copyright 2014 Red Hat, Inc.
 *  *
 *  * All rights reserved. This program and the accompanying materials
 *  * are made available under the terms of the Eclipse Public License v1.0
 *  * and Apache License v2.0 which accompanies this distribution.
 *  *
 *  *     The Eclipse Public License is available at
 *  *     http://www.eclipse.org/legal/epl-v10.html
 *  *
 *  *     The Apache License v2.0 is available at
 *  *     http://www.opensource.org/licenses/apache2.0.php
 *  *
 *  * You may elect to redistribute this code under either of these licenses.
 *  *
 *
 */

import java.util.Random;

public class Main {
    private static Random random = new Random();

    /**
     * Create an array of random bytes
     * @param length The length of the created array
     * @return the byte array
     */
    public static byte[] randomByteArray(int length) {
        return randomByteArray(length, false, (byte) 0);
    }

    /**
     * Create an array of random bytes
     * @param length The length of the created array
     * @param avoid If true, the resulting array will not contain avoidByte
     * @param avoidByte A byte that is not to be included in the resulting array
     * @return an array of random bytes
     */
    public static byte[] randomByteArray(int length, boolean avoid, byte avoidByte) {
        byte[] line = new byte[length];
        for (int i = 0; i < length; i++) {
            byte rand;
            do {
                rand = randomByte();
            } while (avoid && rand == avoidByte);

            line[i] = rand;
        }
        return line;
    }

    /**
     * @return a random byte
     */
    public static byte randomByte() {
        return (byte) ((int) (Math.random() * 255) - 128);
    }
}

Related

  1. nextBytes(byte[] bytes)
  2. nextBytes(int count)
  3. nextBytes(int length)
  4. randBytes(int length)
  5. randomByte(byte[] b)
  6. randomBytes()
  7. randomBytes(byte[] bytes)
  8. randomBytes(final int numBytes)
  9. randomBytes(int length)