在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!"轉換為字節數組,然后進行壓縮和解壓操作,最后打印解壓后的字符串。