在Java中可以使用java.util.zip
包中的Deflater
类和Inflater
类来进行数据压缩和解压缩。以下是一个简单的示例代码:
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class ZlibExample {
public static void main(String[] args) {
String data = "Hello, world!";
byte[] compressedData = compress(data.getBytes());
byte[] decompressedData = decompress(compressedData);
System.out.println("Original data: " + data);
System.out.println("Compressed data: " + new String(compressedData));
System.out.println("Decompressed data: " + new String(decompressedData));
}
public static byte[] compress(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
deflater.end();
return outputStream.toByteArray();
}
public static byte[] decompress(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
try {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
} catch (Exception e) {
e.printStackTrace();
}
}
inflater.end();
return outputStream.toByteArray();
}
}
在上面的示例中,compress
方法用于压缩数据,decompress
方法用于解压缩数据。可以通过调用这两个方法来对数据进行压缩和解压缩操作。