在Java中獲取隨機字符串通常有兩種方式:
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);
}
}
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);
}
}
以上兩種方法可以根據需要自定義生成隨機字符串的長度和字符集合。