在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
方法用于解壓縮數據。可以通過調用這兩個方法來對數據進行壓縮和解壓縮操作。