1、引入依赖
<dependency> <groupId>org.lz4</groupId> <artifactId>lz4-java</artifactId> <version>1.8.0</version> <scope>compile</scope> </dependency>
2、工具类
package com.wst.commons.core.utils; import net.jpountz.lz4.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; /** * lz4 解压缩工具类 */ public class Lz4Utils { /** * 压缩 byte数组 * @author JW.zhong * @time 2023/3/20 16:14 * @param srcBytes */ public static byte[] compress(byte srcBytes[]) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); LZ4Compressor compressor = factory.fastCompressor(); LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream( byteOutput, 2048, compressor); compressedOutput.write(srcBytes); compressedOutput.close(); return byteOutput.toByteArray(); } /** * 解压 byte数组 * @author JW.zhong * @time 2023/3/20 16:14 * @param bytes */ public static byte[] uncompress(byte[] bytes) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); LZ4FastDecompressor decompresser = factory.fastDecompressor(); LZ4BlockInputStream lzis = new LZ4BlockInputStream( new ByteArrayInputStream(bytes), decompresser); int count; byte[] buffer = new byte[2048]; while ((count = lzis.read(buffer)) != -1) { baos.write(buffer, 0, count); } lzis.close(); return baos.toByteArray(); } /** * 转换为字符串 * @author JW.zhong * @time 2023/3/20 16:14 * @param data */ public static String uncompressToString(byte[] data) throws IOException { return new String(uncompress(data), StandardCharsets.UTF_8); } }