gcat/src/main/java/org/gcube/gcat/utils/RandomString.java

38 lines
805 B
Java
Raw Normal View History

package org.gcube.gcat.utils;
import java.util.Random;
/**
* @author Lucio Lelii (ISTI - CNR)
2022-04-05 17:32:03 +02:00
* @author Luca Frosini (ISTI - CNR)
*/
public class RandomString {
2019-09-16 14:48:18 +02:00
private static final char[] symbols;
2019-09-16 14:48:18 +02:00
static {
StringBuilder tmp = new StringBuilder();
2019-09-16 14:48:18 +02:00
for(char ch = '0'; ch <= '9'; ++ch)
tmp.append(ch);
2019-09-16 14:48:18 +02:00
for(char ch = 'a'; ch <= 'z'; ++ch)
tmp.append(ch);
symbols = tmp.toString().toCharArray();
2019-09-16 14:48:18 +02:00
}
private final Random random = new Random();
2019-09-16 14:48:18 +02:00
private final char[] buf;
2019-09-16 14:48:18 +02:00
public RandomString(int length) {
2019-09-16 14:48:18 +02:00
if(length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}
2019-09-16 14:48:18 +02:00
public String nextString() {
2019-09-16 14:48:18 +02:00
for(int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}