GZip wiki是一种文件格式和用于文件压缩和解压缩的软件应用程序。gzip 是一个单文件/流无损数据压缩实用程序,其中生成的压缩文件通常具有后缀.gz
字符串(Plain)
➢ 字节 ➤ GZip 数据(Compress)
➦ 字节 ➥ 字符串(Decompress)
String zipData = "Hi Stackoverflow and GitHub";
// String to Bytes
byte[] byteStream = zipData.getBytes();
System.out.println("String Data:"+ new String(byteStream, "UTF-8"));
// Bytes to Compressed-Bytes then to String.
byte[] gzipCompress = gzipCompress(byteStream);
String gzipCompressString = new String(gzipCompress, "UTF-8");
System.out.println("GZIP Compressed Data:"+ gzipCompressString);
// Bytes to DeCompressed-Bytes then to String.
byte[] gzipDecompress = gzipDecompress(gzipCompress);
String gzipDecompressString = new String(gzipDecompress, "UTF-8");
System.out.println("GZIP Decompressed Data:"+ gzipDecompressString);
GZip 字节(Compress)
➥ 文件(*.gz)
➥ 字符串(Decompress)
GZip 文件扩展名为.gz,互联网媒体类型为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(); // You need to close it before using ByteArrayOutputStream
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)
) {
//String gZipString= IOUtils.toString(gzipIS);
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;
}