码迷,mamicode.com
首页 > 编程语言 > 详细

Java如何生成随机字符串?

时间:2017-11-05 23:33:16      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:generate   ber   key   cti   rate   function   number   source   如何   

import java.security.SecureRandom;
import java.util.Random;

public class RandomString {
    public static final String SOURCES =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

    public static void main(String[] args) {
        RandomString rs = new RandomString();
        System.out.println(rs.generateString(new Random() SOURCES 10));
        System.out.println(rs.generateString(new Random() SOURCES 10));
        System.out.println(rs.generateString(new SecureRandom() SOURCES 15));
        System.out.println(rs.generateString(new SecureRandom() SOURCES 15));
    }

    /**
     * Generate a random string.
     *
     * @param random the random number generator.
     * @param characters the characters for generating string.
     * @param length the length of the generated string.
     * @return
     */
    public String generateString(Random random String characters int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(random.nextInt(characters.length()));
        }
        return new String(text);
    }
}

Java如何生成随机字符串?

标签:generate   ber   key   cti   rate   function   number   source   如何   

原文地址:http://www.cnblogs.com/qhc1105543773/p/7789151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!