對 001 到 010 的字串分別計算 DigestUtils.shaHex,輸出格式:我的兌換碼為:<hash>。
DecimalFormatimport org.apache.commons.codec.digest.DigestUtils;
import java.text.DecimalFormat;
public class BatchShaHex {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("000"); // 三位數,不足前導零
for (int i = 1; i <= 10; i++) {
String code = df.format(i); // "001", "002" ...
String hash = DigestUtils.shaHex(code); // SHA-1 十六進制
System.out.println("我的兌換碼為:" + hash);
}
}
}
new DecimalFormat("000"):模式字串中 0 表示**必須顯示的數位**,不足補零;# 表示可選數位。DigestUtils.shaHex(String) 內部會用 UTF-8 編碼字串再計算 SHA-1,直接返回十六進制字串,無需手動處理字節數組。DigestUtils.sha256Hex()(Commons Codec 1.10+)。IntStream.rangeClosed(1, 100_000)
.parallel()
.mapToObj(i -> df.format(i))
.map(DigestUtils::shaHex)
.forEach(hash -> System.out.println("我的兌換碼為:" + hash));
DecimalFormat 是 Java 格式化定寬數字的標準工具,配合 DigestUtils 一行代碼搞定批量摘要生成。