可以使用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 = new byte[compressedDataLength];
System.arraycopy(buffer, 0, compressedData, 0, compressedDataLength);
deflater.end();
return compressedData;
}
public static byte[] decompress(byte[] compressedData) {
Inflater inflater = new Inflater();
inflater.setInput(compressedData);
byte[] buffer = new byte[compressedData.length * 2];
int decompressedDataLength;
try {
decompressedDataLength = inflater.inflate(buffer);
} catch (Exception e) {
decompressedDataLength = 0;
}
byte[] decompressedData = new byte[decompressedDataLength];
System.arraycopy(buffer, 0, decompressedData, 0, decompressedDataLength);
inflater.end();
return decompressedData;
}
public static void main(String[] args) {
String data = "Hello, World!";
byte[] compressedData = compress(data.getBytes());
System.out.println("Compressed data: " + new String(compressedData));
byte[] decompressedData = decompress(compressedData);
System.out.println("Decompressed data: " + new String(decompressedData));
}
}
在上面的示例中,compress()
方法用于對數據進行壓縮,decompress()
方法用于對壓縮后的數據進行解壓。在main()
方法中,我們演示了如何壓縮和解壓數據。