1. 程式人生 > 實用技巧 >隨機生成字串-隨機生成任意長度的字串

隨機生成字串-隨機生成任意長度的字串

public class RandomStrCreator {

    private static final String[] tmp = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
            "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            
"w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };//,"+","/" private static Random rand = new Random(); public static String createRandomStr(int i) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < i; j++) { sb.append(tmp[rand.nextInt(tmp.length)]); }
return sb.toString(); } public static void main(String[] args) { long currentTimeMillis = System.currentTimeMillis(); String str = createRandomStr(128); System.out.println(str); System.out.println(System.currentTimeMillis() - currentTimeMillis); } }

結果:

6DAcWg7ilbxbH0WLUWhSScHxSN7AZr065KobhOnB4tIqLNdtgHsA4uzGg91W2jEqfhWn8KjpcuRAHhkSjdSawjkUVefzqCQcTUMBPVe0psnutAHxSh74I1PJiWFkHVxl

0