I call a service that returns a gzip file. I have data like InputStream (kindly javax.activation.DataHandler.getInputStream(); ) from the answer.
What I would like to do without writing anything to the disk, get an InputStream of unpacked data in a file that is in the archive. The compressed file in this case is an xml document that I am trying to untie with javax.xml.bind.Unmarshaller , which accepts an InputStream.
I'm currently trying to write an InputStream to an OutputStream (decompress data) and then I will need to write it back to an InputStream. It doesn't work yet, so I thought I'd see if the approach would be better (I hope so).
I can write the initial InputStream to disk and get the gz file, and then read this file, extract the compressed file from it and go from there, but I would rather save it all in memory.
Update 1: Here is my current one (does not work - the exception is "Not in GZIP format"):
ByteArrayInputStream xmlInput = null; try { InputStream in = dh.getInputStream(); //dh is a javax.activation.DataHandler BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream bo = new ByteArrayOutputStream(); int bytes_read = 0; byte[] dataBuf = new byte[4096]; while ((bytes_read = bis.read(dataBuf)) != -1) { bo.write(dataBuf, 0, bytes_read); } ByteArrayInputStream bin = new ByteArrayInputStream(bo.toByteArray()); GZIPInputStream gzipInput = new GZIPInputStream(bin); ByteArrayOutputStream out = new ByteArrayOutputStream(); dataBuf = new byte[4096];; bytes_read = 0; while ((bytes_read = gzipInput.read(dataBuf)) > 0) { out.write(dataBuf, 0, bytes_read); } xmlInput = new ByteArrayInputStream(out.toByteArray());
If instead of writing to ByteArrayOutputStream the first time I write to FileOutputStream, I get a compressed file (which I can open manually to get the XML file inside) and the service (eBay) says that it should be a gzip file so I'm not sure why I get the error "Not in gzip format".
Update 2: I tried something a little different - the same error ("Not in GZIP format"). Wow, I just tried to end this bracket with half an hour. Anyway, here is my second attempt, which still doesn't work:
ByteArrayInputStream xmlInput = null; try { GZIPInputStream gzipInput = new GZIPInputStream(dh.getInputStream()); ByteArrayOutputStream bo = new ByteArrayOutputStream(); int bytes_read = 0; byte[] dataBuf = new byte[4096]; while ((bytes_read = gzipInput.read(dataBuf)) != -1) { bo.write(dataBuf, 0, bytes_read); } xmlInput = new ByteArrayInputStream(bo.toByteArray());
java io gzip gzipinputstream
Ryan elkins
source share