在Java中获取随机字符串通常有两种方式:
- 使用Random类生成随机字符序列
import java.util.Random; public class RandomStringGenerator { private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; public static String generateRandomString(int length) { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { int index = random.nextInt(CHARACTERS.length()); sb.append(CHARACTERS.charAt(index)); } return sb.toString(); } public static void main(String[] args) { String randomString = generateRandomString(10); System.out.println(randomString); } }
- 使用UUID类生成随机字符串
import java.util.UUID; public class RandomStringGenerator { public static String generateRandomString() { return UUID.randomUUID().toString().replaceAll("-", ""); } public static void main(String[] args) { String randomString = generateRandomString(); System.out.println(randomString); } }
以上两种方法可以根据需要自定义生成随机字符串的长度和字符集合。