首页
学习
活动
专区
工具
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方法对压缩后的字节数组进行解压缩,并打印解压缩后的结果。

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

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

相关·内容

领券