我如何创建一个字典对象传递给Zstd.compress?



我在Java中使用Zstd压缩来压缩大型JSON有效负载。我正在使用来自Java的zstd-jni库的方法。我从JSON字符串中创建了一个字节数组,并使用了这个方法。

public static byte[] compress(byte[] var0, int var1)

我读到ZSTD在压缩和解压缩过程中传递字典时会给出更优的结果。我如何创建一个ZstdDictCompress对象?我应该传递给构造函数什么字节数组和整数?

public static long compress(byte[] var0, byte[] var1, ZstdDictCompress var2)

此示例用于https://github.com/luben/zstd-jni。

首先,你需要得到很多你的产品的样品。你不应该只使用一个或几个样本。之后你可以训练你的字典:

List<String> jsons = ...; // List of your jsons samples
ZstdDictTrainer trainer = new ZstdDictTrainer(1024 * 1024, 16 * 1024); // 16 KB dictionary
for(String json : jsons) {
    trainer.addSample(json.getBytes(StandardCharsets.UTF_8));
}
byte[] dictionary = trainer.trainSamples();

现在你有你的字典在字节数组。

下一步是使用相同的

// Compress
byte[] json = jsonString.getBytes(StandardCharsets.UTF_8);
ZstdDictCompress zstdDictCompress = new ZstdDictCompress(dictionary, Zstd.defaultCompressionLevel());
byte[] compressed = Zstd.compress(json, zstdDictCompress);
// Tricky moment, you have to pass json full length to decompress method
int jsonFullLength = json.length;
// Decompress
ZstdDictDecompress zstdDictDecompress = new ZstdDictDecompress(dictionary);
byte[] decompressed = Zstd.decompress(compressed, zstdDictDecompress, jsonFullLength);
String jsonString2 = new String(decompressed, StandardCharsets.UTF_8);

就是这样!

最新更新