java - DeflatorInputStream and DeflatorOutputStream do not reconstruct the original data -


i want compress data, came across deflatorinputstream & deflatoroutputstream classes. however, following example shows can't seem reconstruct original data when using these classes.

when switch zipinputstream , zipoutputstream work, since don't need zip files per se, thought generic compression better. i'm interested in understanding why example doesn't work.

//create "random" data int byteslength = 1024; byte[] bytes = new byte[byteslength]; for(int = 0; < byteslength; i++) {      bytes[i] = (byte) (i % 10); }  //compress data, , write somewhere (a byte array example) bytearrayoutputstream arrayoutputstream = new bytearrayoutputstream(); deflateroutputstream outputstream = new deflateroutputstream(arrayoutputstream); outputstream.write(bytes);  //read , decompress data byte[] readbuffer = new byte[5000]; bytearrayinputstream arrayinputstream = new bytearrayinputstream(arrayoutputstream.tobytearray()); deflaterinputstream inputstream = new deflaterinputstream(arrayinputstream); int read = inputstream.read(readbuffer);  //should hold original (reconstructed) data byte[] actuallyread = arrays.copyof(readbuffer, read);  //results differ - print false system.out.println(arrays.equals(bytes, actuallyread)); 

blame historical precedent. on unix, function used reverse deflate called inflate. so, unlike alot of other java io classes, input , output stream pair not have (obviously) matching names.

the deflateroutputstream doesn't allow reverse deflation, instead deflates bytes passed sink source. deflaterinputstream also deflates, performs action data flows source sink.

in order read data in uncompressed (inflated) format, need use inflaterinputstream:

inflaterinputstream inputstream = new inflaterinputstream(arrayinputstream); 

also, because possible not compressed data stream in 1 read call, need use loop. this:

int read; byte[] finalbuf = new byte[0], swapbuf; byte[] readbuffer = new byte[5012];  bytearrayinputstream arrayinputstream = new bytearrayinputstream(         compressed); inflaterinputstream inputstream = new inflaterinputstream(         arrayinputstream); while ((read = inputstream.read(readbuffer)) != -1) {     system.out.println("intermediate read: " + read);     swapbuf = finalbuf;     finalbuf = new byte[swapbuf.length + read];     system.arraycopy(swapbuf, 0, finalbuf, 0, swapbuf.length);     system.arraycopy(readbuffer, 0, finalbuf, swapbuf.length, read); } 

finally, make sure either flush deflater output stream prior retrieving compressed bytes (or alternatively close stream).


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -