GZIPCompressingInputStream extends DeflaterInputStream { @Override public int read(final byte b[], final int off, final int len) throws IOException { int count = 0; if (part == Part.HEADER) { count = Math.min(len, GZIP_HEADER.length - position); System.arraycopy(GZIP_HEADER, position, b, off, count); position += count; if (position == GZIP_HEADER.length) part = Part.BODY; } if (part == Part.BODY && count < len) { final int i = len - count; final int r = super.read(b, off + count, i); if (r < i) { createTrailer(); part = Part.TRAILER; position = 0; } if (r >= 0) count += r; } if (part == Part.TRAILER && count < len) { final int i = Math.min(len - count, GZIP_TRAILER.length - position); if (i > 0) { System.arraycopy(GZIP_TRAILER, position, b, off + count, i); position += i; count += i; } } return (count > 0 ? count : -1) ; } GZIPCompressingInputStream(final InputStream in); @Override int read(final byte b[], final int off, final int len);  }
@Test public void testCompression() { final File comF = TestUtils.getPath("compression").resolve("compressed.gz").toFile(); final File decF = TestUtils.getPath("compression").resolve("decompressed.jpg").toFile(); try { final File uncF = TestUtils.getPath("compression/uncompressed.jpg").toFile(); final byte[] buffer = new byte[512]; try (GZIPCompressingInputStream cfis = new GZIPCompressingInputStream(new FileInputStream(uncF)); FileOutputStream fos = new FileOutputStream(comF)) { int r = 0; while ( (r = cfis.read(buffer, 0, 512)) > 0 ) { fos.write(buffer, 0, r); } } try (GZIPInputStream decfis = new GZIPInputStream(new FileInputStream(comF)); FileOutputStream fos = new FileOutputStream(decF)) { int r = 0; while ( (r = decfis.read(buffer, 0, 512)) > 0 ) { fos.write(buffer, 0, r); } } try (FileInputStream fis1 = new FileInputStream(uncF); FileInputStream fis2 = new FileInputStream(decF)) { final byte[] buffer2 = new byte[512]; int r = 0; int r2 = 0; while ( ((r = fis1.read(buffer, 0, 512)) > 0) & ((r2 = fis2.read(buffer2, 0, 512)) > 0)) { assertEquals(r, r2); assertArrayEquals(buffer, buffer2); } assertEquals(r, r2); } } catch (final IOException ex) { Logger.getLogger(GZIPCompressingInputStreamTest.class.getName()).log(Level.SEVERE, null, ex); fail(); } finally { if (comF.exists()) comF.delete(); if (decF.exists()) decF.delete(); } }