I wrote a simple piece of Java code that takes a string, converts it to byte [], and then compresses it using Gzip. He then decompresses the result to return the byte [], which now contains one extra byte of the byte. Why is there a dirt bike here?
public static void main (String [] args) throws Exception {
String testString = "Sample String here";
byte[] originalBytes = testString.getBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write(originalBytes);
gzos.close();
byte[] compressedBytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(compressedBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
ByteArrayOutputStream dbaos = new ByteArrayOutputStream();
while(gzis.available() > 0) {
dbaos.write(gzis.read());
}
byte[] decompressedBytes = dbaos.toByteArray();
String decompressedString = new String(decompressedBytes);
System.out.println(">>" + decompressedString + "<<");
System.out.println("Size of bytes before: " + originalBytes.length);
System.out.println("Size of bytes after: " + decompressedBytes.length);
}
Conclusion:
>>Sample String here <<
Size of bytes before: 18
Size of bytes after: 19
Can someone tell me why there is a byte for garbage? How can I get rid of it WITHOUT changing the code setting above?
source
share