I am attempting to convert the gzipped body of a HTTP response to plaintext. I\'ve taken the byte array of this response and converted it to a ByteArrayInputStream. I\'ve th
GZipwiki is a file format and a software application used for file compression and decompression. gzip is a single-file/stream lossless data compression utility, where the resulting compressed file generally has the suffix .gz
String
(Plain)
➢ Bytes ➤ GZip-Data(Compress)
➦ Bytes ➥ String(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-Bytes
(Compress)
➥ File(*.gz)
➥ String(Decompress)
GZip Filename extension .gz and Internet media type is 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"));
Following functions are used for compression and decompression.
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;
}
You can use the StringWriter to write to String