美文网首页
Java如何生成随机字符串

Java如何生成随机字符串

作者: Sherlockkk | 来源:发表于2018-01-06 17:57 被阅读33次

    没什么好说的,直接上代码

    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如何生成随机字符串

          本文链接:https://www.haomeiwen.com/subject/dtoynxtx.html