Java Code Examples for java.util.zip.Inflater

Following code examples demonstrate how to use java.util.zip.Inflaterfrom android. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use java.util.zip.Inflaterand various code implementation of this class.

    private void setDictionary(byte[] b, int off, int len) {
        final gnu.java.util.zip.Inflater gnuInflater = getGNUInflater(this);
        gnuInflater.setDictionary(b, off, len);
    } 


    private void end() {
        getGNUInflater(this).end();
        Inflater_gnuInflater.setObject(this, null);
    } 

    private static long init(boolean nowrap) {
        VEError.unexpected("java.util.zip.Inflater.init should never be called!");
        return 0;
    } 

    private void constructor(boolean nowrap) {
        final gnu.java.util.zip.Inflater gnuInflater = new gnu.java.util.zip.Inflater(nowrap);
        Inflater_gnuInflater.setObject(this, gnuInflater);
    } 

    private void setInput(byte[] b, int off, int len) {
        final gnu.java.util.zip.Inflater gnuInflater = getGNUInflater(this);
        gnuInflater.setInput(b, off, len);
    } 

	public void test_ConstructorZ() {
		byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
		Inflater inflate = new Inflater(true);
		assertNotNull("failed to create the instance of inflater", inflate);
		byte outPutInf[] = new byte[500];
		int r = 0;
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuff1);
				}

				inflate.inflate(outPutInf);
			}
			for (int i = 0; i < byteArray.length; i++) {
				assertEquals("the output array from inflate should contain 0 because the header of inflate and deflate did not match, but this failed",
						0, outPutBuff1[i]);
			}
		} catch (DataFormatException e) {
			r = 1;
		}
		assertEquals("Error: exception should be thrown because of header inconsistency",
				1, r);

	} 

	public void test_getTotalIn() {
		byte outPutBuf[] = new byte[500];
		byte byteArray[] = { 1, 3, 4, 7, 8 };
		byte outPutInf[] = new byte[500];
		int x = 0;
		Deflater deflate = new Deflater(1);
		deflate.setInput(byteArray);
		while (!(deflate.needsInput())) {
			x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
		}
		deflate.finish();
		while (!(deflate.finished())) {
			x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
		}

		Inflater inflate = new Inflater();
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuf);
				}

				inflate.inflate(outPutInf);
			}
		} catch (DataFormatException e) {
			fail("Input to inflate is invalid or corrupted - getTotalIn");
		}
		assertTrue(
				"the total byte in outPutBuf did not equal the byte returned in getTotalIn",
				inflate.getTotalIn() == deflate.getTotalOut());

		Inflater inflate2 = new Inflater();
		int length = 4;
		try {
			if (inflate2.needsInput()) {
				inflate2.setInput(outPutBuff1, offSet, length);
			}

			inflate2.inflate(outPutInf);

		} catch (DataFormatException e) {
			fail("Input to inflate is invalid or corrupted - getTotalIn");
		}
		assertTrue(
				"total byte dictated by length did not equal byte returned in getTotalIn",
				inflate2.getTotalIn() == length);
	} 

    
    public void test_getBytesRead() throws DataFormatException,
            UnsupportedEncodingException {
        Deflater def = new Deflater();
        Inflater inf = new Inflater();
        assertEquals(0, def.getTotalIn());
        assertEquals(0, def.getTotalOut());
        assertEquals(0, def.getBytesRead());
        String inputString = "blahblahblah??";
        byte[] input = inputString.getBytes("UTF-8");

        byte[] output = new byte[100];
        def.setInput(input);
        def.finish();
        def.deflate(output);
        inf.setInput(output);
        int compressedDataLength =inf.inflate(input);
        assertEquals(16, inf.getTotalIn());
        assertEquals(compressedDataLength, inf.getTotalOut());
        assertEquals(16, inf.getBytesRead());
    } 

	public void test_getRemaining() {
		byte byteArray[] = { 1, 3, 5, 6, 7 };
		Inflater inflate = new Inflater();
		assertEquals("upon creating an instance of inflate, getRemaining returned a non zero value",
				0, inflate.getRemaining());
		inflate.setInput(byteArray);
		assertTrue(
				"getRemaining returned zero when there is input in the input buffer",
				inflate.getRemaining() != 0);
	} 

	public void test_Constructor() {
		Inflater inflate = new Inflater();
		assertNotNull("failed to create the instance of inflater",
				inflate);
	} 

	public void test_needsInput() {
		Inflater inflate = new Inflater();
		assertTrue(
				"needsInput give the wrong boolean value as a result of no input buffer",
				inflate.needsInput());

		byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
		inflate.setInput(byteArray);
		assertFalse(
				"methodNeedsInput returned true when the input buffer is full",
				inflate.needsInput());

		inflate.reset();
		byte byteArrayEmpty[] = new byte[0];
		inflate.setInput(byteArrayEmpty);
		assertTrue(
				"needsInput give wrong boolean value as a result of an empty input buffer",
				inflate.needsInput());
	} 

	public void test_finished() {
		byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
		Inflater inflate = new Inflater(false);
		byte outPutInf[] = new byte[500];
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuff1);
				}

				inflate.inflate(outPutInf);
			}
			assertTrue(
					"the method finished() returned false when no more data needs to be decompressed",
					inflate.finished());
		} catch (DataFormatException e) {
			fail("Invalid input to be decompressed");
		}
		for (int i = 0; i < byteArray.length; i++) {
			assertTrue(
					"Final decompressed data does not equal the original data",
					byteArray[i] == outPutInf[i]);
		}
		assertEquals("final decompressed data contained more bytes than original - finished()",
				0, outPutInf[byteArray.length]);
	} 

    public void testInflate() throws Exception {
        Inflater inf = new Inflater();
        int res = inf.inflate(new byte[0], 0, 0);

        assertEquals(0, res);

        Inflater inflater = new Inflater();
        byte[] b = new byte[1024];
        assertEquals(0, inflater.inflate(b));
        inflater.end();

        inflater = new Inflater();
        inflater.setInput(new byte[] { -1 });
        try {
            inflater.inflate(b);

            assertTrue(inflater.needsInput());
        } catch (DataFormatException e) {
        }

        inflater = new Inflater();
        inflater.setInput(new byte[] { -1, -1, -1 });
        try {
            inflater.inflate(b);
        } catch (DataFormatException e) {
        }
    } 

	public void test_needsDictionary() {
		byte outPutInf[] = new byte[500];

		Inflater inflateDiction = new Inflater();
		if (inflateDiction.needsInput()) {
			inflateDiction.setInput(outPutDiction);
		}
		try {
			assertEquals("should return 0 because needs dictionary",
					0, inflateDiction.inflate(outPutInf));
		} catch (DataFormatException e) {
			fail("Should not cause exception");
		}
		assertTrue(
				"method needsDictionary returned false when dictionary was used in deflater",
				inflateDiction.needsDictionary());

		Inflater inflate = new Inflater();
		try {
			inflate.setInput(outPutBuff1);
			inflate.inflate(outPutInf);
			assertFalse(
					"method needsDictionary returned true when dictionary was not used in deflater",
					inflate.needsDictionary());
		} catch (DataFormatException e) {
			fail(
					"Input to inflate is invalid or corrupted - needsDictionary");
		}

        Inflater inf = new Inflater();
        assertFalse(inf.needsDictionary());
        assertEquals(0,inf.getTotalIn());
        assertEquals(0,inf.getTotalOut());
        assertEquals(0,inf.getBytesRead());
        assertEquals(0,inf.getBytesWritten());
	} 

	public void test_end() {
		byte byteArray[] = { 5, 2, 3, 7, 8 };

		int r = 0;
		Inflater inflate = new Inflater();
		inflate.setInput(byteArray);
		inflate.end();
		try {
			inflate.reset();
			inflate.setInput(byteArray);
		} catch (NullPointerException e) {
			r = 1;
		}
		assertEquals("inflate can still be used after end is called", 1, r);

		Inflater i = new Inflater();
		i.end();
		i.end();
	} 

	public void test_getAdler() {
		byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };

		Inflater inflateDiction = new Inflater();
		inflateDiction.setInput(outPutDiction);
		if (inflateDiction.needsDictionary() == true) {
			Adler32 adl = new Adler32();
			adl.update(dictionaryArray);
			long checkSumR = adl.getValue();
			assertTrue(
					"the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
					checkSumR == inflateDiction.getAdler());
		}
	} 

	public void test_reset() {
		byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
		byte outPutInf[] = new byte[100];
		int y = 0;
		Inflater inflate = new Inflater();
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuff1);
				}
				y += inflate.inflate(outPutInf, y, outPutInf.length - y);
			}
		} catch (DataFormatException e) {
			fail("Invalid input to be decompressed");
		}
		for (int i = 0; i < byteArray.length; i++) {
			assertTrue(
					"Final decompressed data does not equal the original data",
					byteArray[i] == outPutInf[i]);
		}
		assertEquals("final decompressed data contained more bytes than original - reset",
				0, outPutInf[byteArray.length]);


		inflate.reset();
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuff1);
				}
				inflate.inflate(outPutInf);
			}
		} catch (DataFormatException e) {
			fail("Invalid input to be decompressed");
		}
		for (int i = 0; i < byteArray.length; i++) {
			assertTrue(
					"Final decompressed data does not equal the original data",
					byteArray[i] == outPutInf[i]);
		}
		assertEquals("final decompressed data contained more bytes than original - reset",
				0, outPutInf[byteArray.length]);

	} 

	public void test_getTotalOut() {
		byte outPutBuf[] = new byte[500];
		byte byteArray[] = { 1, 3, 4, 7, 8 };
		int y = 0;
		int x = 0;
		Deflater deflate = new Deflater(1);
		deflate.setInput(byteArray);
		while (!(deflate.needsInput())) {
			x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
		}
		deflate.finish();
		while (!(deflate.finished())) {
			x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
		}

		Inflater inflate = new Inflater();
		byte outPutInf[] = new byte[500];
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuf);
				}

				y += inflate.inflate(outPutInf);
			}
		} catch (DataFormatException e) {
			fail("Input to inflate is invalid or corrupted - getTotalIn");
		}

		assertTrue(
				"the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
				y == inflate.getTotalOut());
		assertTrue(
				"the total number of bytes to be compressed does not equal the total bytes decompressed",
				inflate.getTotalOut() == deflate.getTotalIn());

		inflate.reset();
		y = 0;
		int length = 4;
		try {
			while (!(inflate.finished())) {
				if (inflate.needsInput()) {
					inflate.setInput(outPutBuf);
				}

				y += inflate.inflate(outPutInf, offSet, length);
			}
		} catch (DataFormatException e) {
			System.out
					.println("Input to inflate is invalid or corrupted - getTotalIn");
		}
		assertTrue(
				"the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
				y == inflate.getTotalOut());
		assertTrue(
				"the total number of bytes to be compressed does not equal the total bytes decompressed",
				inflate.getTotalOut() == deflate.getTotalIn());
	} 

    public void test_getBytesWritten() throws DataFormatException, UnsupportedEncodingException {
        Deflater def = new Deflater();
        Inflater inf = new Inflater();
        assertEquals(0, def.getTotalIn());
        assertEquals(0, def.getTotalOut());
        assertEquals(0, def.getBytesWritten());
        String inputString = "blahblahblah??";
        byte[] input = inputString.getBytes("UTF-8");

        byte[] output = new byte[100];
        def.setInput(input);
        def.finish();
        def.deflate(output);
        inf.setInput(output);
        int compressedDataLength =inf.inflate(input);
        assertEquals(16, inf.getTotalIn());
        assertEquals(compressedDataLength, inf.getTotalOut());
        assertEquals(14, inf.getBytesWritten());
    } 

    @Category(Draft.class)
    public void create_Inflater()
    throws Exception {
        @SuppressWarnings("unused")
        final Inflater sut = new Inflater();
    } 

    public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Inflater() {
        new InflaterOutputStream(os, new Inflater());

        try {
            new InflaterOutputStream(null, new Inflater());
            fail("Should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        try {
            new InflaterOutputStream(os, null);
            fail("Should throw NullPointerException");
        } catch (NullPointerException e) {
        }
    } 

    public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_InflaterI() {
        new InflaterOutputStream(os, new Inflater(), 20);

        try {
            new InflaterOutputStream(null, null, 10);
            fail("Should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        try {
            new InflaterOutputStream(null, new Inflater(), -1);
            fail("Should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        try {
            new InflaterOutputStream(os, null, -1);
            fail("Should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        try {
            new InflaterOutputStream(null, null, -1);
            fail("Should throw NullPointerException");
        } catch (NullPointerException e) {
        }

        try {
            new InflaterOutputStream(os, new Inflater(), 0);
            fail("Should throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
        }

        try {
            new InflaterOutputStream(os, new Inflater(), -10000);
            fail("Should throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
        }
    } 

	public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Inflater() throws IOException {
		byte byteArray[] = new byte[100];
		Inflater inflate = new Inflater();
		InflaterInputStream inflatIP = new InflaterInputStream(infile,
				inflate);

		inflatIP.close();
	} 

	public void test_skipJ2() throws IOException {
		int result = 0;
		int buffer[] = new int[100];
		byte orgBuffer[] = { 1, 3, 4, 7, 8 };

		InputStream infile = Support_Resources
		Inflater inflate = new Inflater();
		InflaterInputStream inflatIP = new InflaterInputStream(infile,
				inflate, 10);
		long skip;
		try {
			skip = inflatIP.skip(Integer.MIN_VALUE);
			fail("Expected IllegalArgumentException when skip() is called with negative parameter");
		} catch (IllegalArgumentException e) {
		}
		inflatIP.close();

		InputStream infile2 = Support_Resources
		InflaterInputStream inflatIP2 = new InflaterInputStream(infile2);


		skip = inflatIP2.skip(Integer.MAX_VALUE);
		assertEquals("method skip() returned wrong number of bytes skipped",
				5, skip);

		InputStream infile3 = Support_Resources
		InflaterInputStream inflatIP3 = new InflaterInputStream(infile3);
		skip = inflatIP3.skip(2);
		assertEquals("the number of bytes returned by skip did not correspond with its input parameters",
				2, skip);
		int i = 0;
		result = 0;
		while ((result = inflatIP3.read()) != -1) {
			buffer[i] = result;
			i++;
		}
		inflatIP2.close();

		for (int j = 2; j < orgBuffer.length; j++) {
			assertTrue(
				"original compressed data did not equal decompressed data",
				buffer[j - 2] == orgBuffer[j]);
		}
	} 

	public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI() throws IOException {
		int result = 0;
		int buffer[] = new int[500];
		Inflater inflate = new Inflater();
		InflaterInputStream inflatIP = new InflaterInputStream(infile,
				inflate, 1);

		int i = 0;
		while ((result = inflatIP.read()) != -1) {
			buffer[i] = result;
			i++;
		}
		inflatIP.close();
	} 

	public void test_read() throws IOException {
		int result = 0;
		int buffer[] = new int[500];
		byte orgBuffer[] = { 1, 3, 4, 7, 8 };
		InputStream infile = Support_Resources
		Inflater inflate = new Inflater();
		InflaterInputStream inflatIP = new InflaterInputStream(infile,
				inflate);

		int i = 0;
		while ((result = inflatIP.read()) != -1) {
			buffer[i] = result;
			i++;
		}
		inflatIP.close();

		for (int j = 0; j < orgBuffer.length; j++) {
			assertTrue(
				"original compressed data did not equal decompressed data",
				buffer[j] == orgBuffer[j]);
		}
	} 

Advertisement
Javadoc
This class provides support for general purpose decompression using the popular ZLIB compression lib

rary. The ZLIB compression library was initially developed as part of the PNG graphics standard and is not protected by patents. It is fully described in the specifications at the java.util.zip package description.

The following code fragment demonstrates a trivial compression and decompression of a string using Deflater and Inflater. try { // Encode a String into bytes String inputString = "blahblahblah\u20AC\u20AC"; byte[] input = inputString.getBytes("UTF-8"); // Compress the bytes byte[] output = new byte[100]; Deflater compresser = new Deflater(); compresser.setInput(input); compresser.finish(); int compressedDataLength = compresser.deflate(output); // Decompress the bytes Inflater decompresser = new Inflater(); decompresser.setInput(output, 0, compressedDataLength); byte[] result = new byte[100]; int resultLength = decompresser.inflate(result); decompresser.end(); // Decode the bytes into a String String outputString = new String(result, 0, resultLength, "UTF-8"); catch(java.io.UnsupportedEncodingException ex) { // handle catch (java.util.zip.DataFormatException ex) { // handle @see Deflater @author David Connelly

Read More
Advertisement