Java Random String generateRandomString(int length)

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

Description

Generate random chars string of given length.

License

Open Source License

Parameter

Parameter Description
length a parameter

Return

a random string of given length.

Declaration

public static String generateRandomString(int length) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2016 GreenVulcano ESB Open Source Project.
 * All rights reserved./*from   w w w . ja va2s .c  o  m*/
 *
 * This file is part of GreenVulcano ESB.
 *
 * GreenVulcano ESB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GreenVulcano ESB 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with GreenVulcano ESB. If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/

import java.util.Base64;

import java.util.Random;

public class Main {
    private static Random rnd = new Random(System.currentTimeMillis());

    /**
     * Generate random chars string of given <code>length</code>.
     * 
     * @param length
     * @return a random string of given <code>length</code>.
     */
    public static String generateRandomString(int length) {
        int blen = ((length + 3) / 4) * 3; // base 64: 3 bytes = 4 chars
        byte[] bval = new byte[blen];
        rnd.nextBytes(bval);
        // change '/' and '\' with '$' in case the string is used as file name
        return new String(Base64.getEncoder().encode(bval), 0, length).replace('/', '$');
    }
}

Related

  1. generateRandomString(int length)
  2. generateRandomString(int length)
  3. generateRandomString(int length)
  4. generateRandomString(int length)
  5. generateRandomString(int length)
  6. generateRandomString(int length)
  7. generateRandomString(int length)
  8. generateRandomString(int length)
  9. generateRandomString(int length)