Here you can find the source of getRandomString(int length, String charset)
Parameter | Description |
---|---|
length | of the random string to generate |
charset | use to generate random value |
public static String getRandomString(int length, String charset)
//package com.java2s; /*//from w w w. ja v a 2 s.c o m * Cerberus Copyright (C) 2013 vertigo17 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of Cerberus. * * Cerberus 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. * * Cerberus 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 Cerberus. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Random; public class Main { /** * Generate a random string using current time and charset * * @param length of the random string to generate * @param charset use to generate random value * @return random string, empty if charset is null or length <= 0 */ public static String getRandomString(int length, String charset) { Random rand = new Random(System.currentTimeMillis()); StringBuilder sb = new StringBuilder(); if (charset == null) { return sb.toString(); } for (int i = 0; i < length; i++) { int pos = rand.nextInt(charset.length()); sb.append(charset.charAt(pos)); } return sb.toString(); } }