可以使用Java中提供的Inflater
和Deflater
类来实现zlib压缩和解压功能。
以下是一个简单的示例代码,演示如何使用Java实现zlib压缩和解压:
import java.util.zip.Deflater; import java.util.zip.Inflater; public class ZlibExample { public static byte[] compress(byte[] data) { Deflater deflater = new Deflater(); deflater.setInput(data); deflater.finish(); byte[] buffer = new byte[data.length]; int compressedDataLength = deflater.deflate(buffer); byte[] compressedData = https://www.yisu.com/ask/new byte[compressedDataLength];"Hello, World!"; byte[] compressedData = https://www.yisu.com/ask/compress(data.getBytes());"Compressed data: " + new String(compressedData)); byte[] decompressedData = https://www.yisu.com/ask/decompress(compressedData);"Decompressed data: " + new String(decompressedData)); } }
在上面的示例中,compress()
方法用于对数据进行压缩,decompress()
方法用于对压缩后的数据进行解压。在main()
方法中,我们演示了如何压缩和解压数据。