GZipwiki 是一种文件格式和软件应用程序,用于文件的压缩和解压缩。gzip 是一个单文件/流无损数据压缩实用程序,生成的压缩文件通常具有后缀.gz
字符串(明文)
➢ 字节 ➤ GZip-Data(压缩)
➦ 字节 ➥ 字符串(解压)
String zipData = "Hi Stackoverflow and GitHub";
byte[] byteStream = zipData.getBytes();
System.out.println("String Data:"+ new String(byteStream, "UTF-8"));
byte[] gzipCompress = gzipCompress(byteStream);
String gzipCompressString = new String(gzipCompress, "UTF-8");
System.out.println("GZIP Compressed Data:"+ gzipCompressString);
byte[] gzipDecompress = gzipDecompress(gzipCompress);
String gzipDecompressString = new String(gzipDecompress, "UTF-8");
System.out.println("GZIP Decompressed Data:"+ gzipDecompressString);
GZip-Bytes(压缩)
➥ 文件 (*.gz)
➥ 字符串(解压)
GZip 的文件扩展名为 .gz,Internet 媒体类型为 application/gzip
。
File textFile = new File("C:/Yash/GZIP/archive.gz.txt");
File zipFile = new File("C:/Yash/GZIP/archive.gz");
org.apache.commons.io.FileUtils.writeByteArrayToFile(textFile, byteStream);
org.apache.commons.io.FileUtils.writeByteArrayToFile(zipFile, gzipCompress);
FileInputStream inStream = new FileInputStream(zipFile);
byte[] fileGZIPBytes = IOUtils.toByteArray(inStream);
byte[] gzipFileDecompress = gzipDecompress(fileGZIPBytes);
System.out.println("GZIPFILE Decompressed Data:"+ new String(gzipFileDecompress, "UTF-8"));
以下函数用于压缩和解压缩。
public static byte[] gzipCompress(byte[] uncompressedData) {
byte[] result = new byte[]{};
try (
ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
GZIPOutputStream gzipOS = new GZIPOutputStream(bos)
) {
gzipOS.write(uncompressedData);
gzipOS.close();
result = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static byte[] gzipDecompress(byte[] compressedData) {
byte[] result = new byte[]{};
try (
ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPInputStream gzipIS = new GZIPInputStream(bis)
) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzipIS.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
result = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}