当前位置:   article > 正文

Java生成指定长度的随机字符串的三种方法_将 secret 的值更改为长随机字符串

将 secret 的值更改为长随机字符串

1 自定义随机字符串方法一(A-Z,a-z,0-9)

  1. //生成指定length的随机字符串(A-Z,a-z,0-9)
  2. public static String getRandomString(int length) {
  3. String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  4. Random random = new Random();
  5. StringBuffer sb = new StringBuffer();
  6. for (int i = 0; i < length; i++) {
  7. int number = random.nextInt(str.length());
  8. sb.append(str.charAt(number));
  9. }
  10. return sb.toString();
  11. }

 

2 自定义随机字符串方法二(A-Z,a-z,0-9)

  1. //生成指定length的随机字符串(A-Z,a-z,0-9)
  2. public static String getRandomString2(int length) {
  3. Random random = new Random();
  4. StringBuffer sb = new StringBuffer();
  5. for (int i = 0; i < length; i++) {
  6. int number = random.nextInt(3);
  7. long result = 0;
  8. switch (number) {
  9. case 0:
  10. result = Math.round(Math.random() * 25 + 65);
  11. sb.append(String.valueOf((char) result));
  12. break;
  13. case 1:
  14. result = Math.round(Math.random() * 25 + 97);
  15. sb.append(String.valueOf((char) result));
  16. break;
  17. case 2:
  18. sb.append(String.valueOf(new Random().nextInt(10)));
  19. break;
  20. }
  21. }
  22. return sb.toString();
  23. }

 

3 org.apache.commons.lang包下的RandomStringUtils类

  1. //生成指定length的随机字符串(A-Z,a-z,0-9)
  2. String str = RandomStringUtils.randomAlphanumeric(32);

 

  运行结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/758214
推荐阅读
相关标签
  

闽ICP备14008679号