首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Java中解压缩字节数组

在Java中解压缩字节数组可以使用java.util.zip包中的Inflater类。以下是一个完整的示例代码:

代码语言:java
复制
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class ByteArrayCompression {
    public static byte[] compress(byte[] input) throws IOException {
        Deflater deflater = new Deflater();
        deflater.setInput(input);
        deflater.finish();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length);
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int count = deflater.deflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        outputStream.close();

        return outputStream.toByteArray();
    }

    public static byte[] decompress(byte[] input) throws IOException, DataFormatException {
        Inflater inflater = new Inflater();
        inflater.setInput(input);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length);
        byte[] buffer = new byte[1024];
        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        outputStream.close();

        return outputStream.toByteArray();
    }

    public static void main(String[] args) {
        try {
            String inputString = "Hello, World!";
            byte[] inputBytes = inputString.getBytes();

            // 压缩字节数组
            byte[] compressedBytes = compress(inputBytes);
            System.out.println("Compressed: " + new String(compressedBytes));

            // 解压缩字节数组
            byte[] decompressedBytes = decompress(compressedBytes);
            System.out.println("Decompressed: " + new String(decompressedBytes));
        } catch (IOException | DataFormatException e) {
            e.printStackTrace();
        }
    }
}

这个示例代码中,我们定义了两个方法:compressdecompresscompress方法接收一个字节数组作为输入,使用Deflater类进行压缩,并返回压缩后的字节数组。decompress方法接收一个字节数组作为输入,使用Inflater类进行解压缩,并返回解压缩后的字节数组。

main方法中,我们演示了如何使用这两个方法来压缩和解压缩字节数组。首先,我们将字符串"Hello, World!"转换为字节数组,并调用compress方法进行压缩。然后,我们打印压缩后的字节数组。接下来,我们调用decompress方法对压缩后的字节数组进行解压缩,并打印解压缩后的结果。

请注意,这只是一个简单的示例,实际应用中可能需要处理异常、使用更大的缓冲区等。此外,还可以使用其他压缩算法和库来实现字节数组的压缩和解压缩。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

13分19秒

day07_数组/19-尚硅谷-Java语言基础-数组中的常见异常

13分19秒

day07_数组/19-尚硅谷-Java语言基础-数组中的常见异常

13分19秒

day07_数组/19-尚硅谷-Java语言基础-数组中的常见异常

11分28秒

Java零基础-253-往byte数组中读

30分41秒

120-尚硅谷-图解Java数据结构和算法-数据压缩-赫夫曼编码字节数组

30分41秒

120-尚硅谷-图解Java数据结构和算法-数据压缩-赫夫曼编码字节数组

9分57秒

121-尚硅谷-图解Java数据结构和算法-数据压缩-赫夫曼字节数组封装

9分57秒

121-尚硅谷-图解Java数据结构和算法-数据压缩-赫夫曼字节数组封装

30分1秒

1.尚硅谷全套JAVA教程--基础必备(67.32GB)/尚硅谷Java入门教程,java电子书+Java面试真题(2023新版)/08_授课视频/71-数组-Arrays工具类的使用与数组中的常见异常.mp4

2分23秒

EDI系统日志管理

3分25秒

063_在python中完成输入和输出_input_print

1.3K
领券