gpt4 book ai didi

java - Parse.com 使用 java 创建 objectId

转载 作者:行者123 更新时间:2023-12-02 11:48:39 25 4
gpt4 key购买 nike

我有 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

最佳答案

我在某处发现了这种方法并成功使用它。

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();
}

关于java - Parse.com 使用 java 创建 objectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48028963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com