在Java中使用zlib压缩数据可以通过Java标准库中的Deflater
和Inflater
类来实现。以下是一个示例代码:
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class ZlibCompression {
public static byte[] compressData(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
byte[] buffer = new byte[1024];
int compressedDataLength = deflater.deflate(buffer);
byte[] compressedData = new byte[compressedDataLength];
System.arraycopy(buffer, 0, compressedData, 0, compressedDataLength);
deflater.end();
return compressedData;
}
public static byte[] decompressData(byte[] compressedData) {
Inflater inflater = new Inflater();
inflater.setInput(compressedData);
byte[] buffer = new byte[1024];
int decompressedDataLength = inflater.inflate(buffer);
byte[] decompressedData = new byte[decompressedDataLength];
System.arraycopy(buffer, 0, decompressedData, 0, decompressedDataLength);
inflater.end();
return decompressedData;
}
public static void main(String[] args) {
String input = "Hello, world!";
byte[] inputData = input.getBytes();
byte[] compressedData = compressData(inputData);
byte[] decompressedData = decompressData(compressedData);
String output = new String(decompressedData);
System.out.println(output);
}
}
在上面的示例中,我们定义了compressData
和decompressData
方法来分别压缩和解压数据。在main
方法中,我们先将字符串"Hello, world!"转换为字节数组,然后进行压缩和解压操作,最后打印解压后的字符串。