随笔 - 32,  文章 - 0,  评论 - 6,  阅读 - 76044

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);
    }
}
复制代码

 

posted on   小胡桐  阅读(2949)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示