Java 解压缩 GZIP 数据:简单示例和代码
在 Java 中解码 GZIP 压缩的数据可以使用 Java 的 GZIPInputStream 类。以下是一个简单的示例:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class GzipDecoder {
public static byte[] decode(byte[] compressedData) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedData))) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzipInputStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
return out.toByteArray();
}
public static void main(String[] args) throws IOException {
byte[] compressedData = // 压缩后的数据
byte[] uncompressedData = decode(compressedData);
// 使用解压缩后的数据
}
}
在上面的示例中,decode 方法接收一个压缩后的字节数组,并返回解压后的字节数组。该方法使用 GZIPInputStream 来解压缩数据,并将解压缩后的数据写入一个 ByteArrayOutputStream 中。最后,该方法返回 ByteArrayOutputStream 中的数据。
在 main 方法中,我们可以使用 decode 方法来解压缩数据并使用解压缩后的数据。
原文地址: https://www.cveoy.top/t/topic/nfac 著作权归作者所有。请勿转载和采集!