我有parse.com项目,我想创建objectId。我在此链接中找到了此方法:randomString
:parse-server-cryptoUtils。
export function randomString(size: number): string {
if (size === 0) {
throw new Error('Zero-length randomString is useless.');
}
const chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789');
let objectId = '';
const bytes = randomBytes(size);
for (let i = 0; i < bytes.length; ++i) {
objectId += chars[bytes.readUInt8(i) % chars.length];
}
return objectId;
}
我如何在java上编写这个方法?我无法转换此bytes.readUInt8
。
答案 0 :(得分:1)
我已经找到了这种方法并成功使用它。
public class RandomString {
private static final char[] SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();
private final Random random = new Random();
private final char[] buf;
public RandomString(int length) {
assert length > 0;
buf = new char[length];
}
String nextString() {
for (int i = 0; i < buf.length; i++) {
buf[i] = SYMBOLS[random.nextInt(SYMBOLS.length)];
}
return new String(buf);
}
}
P.S。 Java
中的示例可能看起来像这样的快照:
public static String randomString(int size) {
if (size <= 0)
throw new RuntimeException("Zero-length randomString is useless.");
final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
StringBuilder objectId = new StringBuilder();
Random random = new Random();
for (int i = 0; i < size; ++i)
objectId.append(chars[random.nextInt(Integer.MAX_VALUE) % chars.length]);
return objectId.toString();
}