【工具介绍】Java 解压 lz4 压缩的数据

LZ4 是一种非常高效的压缩算法,以其高速压缩和解压缩速度而闻名,同时保持了相对较好的压缩率。本片博客介绍 Java 如何使用aircompressor进行 LZ4 压缩、解压缩。

Maven 依赖

<dependency>
   <groupId>io.airliftgroupId>
   <artifactId>aircompressorartifactId>
   <version>0.21version>
dependency>

压缩操作

    public void test_lz4_compress() {
        // 要压缩的原始文本
        String originalText = "Hello World From Wzz";
        byte[] inputData = originalText.getBytes(java.nio.charset.StandardCharsets.UTF_8);

        // 创建一个 ByteBuffer 来包装原始数据
        ByteBuffer inputBuffer = ByteBuffer.wrap(inputData);

        Lz4Compressor lz4Compressor = new Lz4Compressor();
        // 估算压缩后的最大长度
        int maxCompressedLength = lz4Compressor.maxCompressedLength(inputData.length);

        // 准备一个 ByteBuffer 来存储压缩后的数据
        ByteBuffer outputBuffer = ByteBuffer.allocate(maxCompressedLength);

        // 创建压缩器实例
        Lz4Compressor compressor = new Lz4Compressor();

        // 执行压缩操作
        compressor.compress(inputBuffer, outputBuffer);

        // 为了从 ByteBuffer 中提取压缩后的数据,需要调用 flip() 方法
        outputBuffer.flip();

        // 将压缩后的数据转换为字节数组
        byte[] compressedData = new byte[outputBuffer.remaining()];
        outputBuffer.get(compressedData);

        // 8AVIZWxsbyBXb3JsZCBGcm9tIFd6eg==
        System.out.println("Base64 encoded string: " + new String(Base64.getEncoder().encode(compressedData)));
    }

执行结果如下:
在这里插入图片描述

后续我将使用这个 Base64 编码后的字符串,展示 lz4 的解压缩操作。

解压缩操作

假设压缩后的数据是 Base64 编码的字节串,解压缩操作如下:

    @Test
    public void test_lz4_decompress() {
        // 假设 compressedContent 是已经从 Base64 解码后的 LZ4 压缩数据字节数组
        byte[] compressedContent = Base64.getDecoder().decode("8AVIZWxsbyBXb3JsZCBGcm9tIFd6eg==");

        // 创建解压缩器实例
        Lz4Decompressor decompressor = new Lz4Decompressor();

        ByteBuffer compressedBuffer = ByteBuffer.wrap(compressedContent);

        // 创建一个足够容纳原始数据的缓冲区
        ByteBuffer decompressedBuffer = ByteBuffer.allocate(64);

        // 执行解压缩操作
        decompressor.decompress(compressedBuffer, decompressedBuffer);

        // 确保解压后的数据位于 ByteBuffer 的开始处
        decompressedBuffer.flip();

        // 将 ByteBuffer 转换为字节数组
        byte[] decompressedBytes = new byte[decompressedBuffer.remaining()];
        decompressedBuffer.get(decompressedBytes);

        // 将字节数组转换为字符串
        String text = new String(decompressedBytes, java.nio.charset.StandardCharsets.UTF_8);

        // 打印解压缩后的文本
        System.out.println(text);
    }

执行结果如下:
在这里插入图片描述

你可能感兴趣的:(java,开发语言,maven,spring,boot)