Example of Deflater and Inflater in Java
April 13, 2013
Deflater in java is used to compress data and Inflater is used to decompress data. Deflater and Inflater use ZLIB library to compress and decompress the data. In the example we have taken a string to compress and then we have decompressed the compressed string.
DeflaterInflaterDemo.java
package com.concretepage; import java.io.UnsupportedEncodingException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; public class DeflaterInflaterDemo { public static void main(String[] arg) throws DataFormatException, UnsupportedEncodingException { String inStr = "Hellow World!"; byte[] data = inStr.getBytes("UTF-8"); byte[] output = new byte[100]; //Compresses the data Deflater compresser = new Deflater(); compresser.setInput(data); compresser.finish(); int bytesAfterdeflate = compresser.deflate(output); System.out.println("Compressed byte number:"+bytesAfterdeflate); //Decompresses the data Inflater decompresser = new Inflater(); decompresser.setInput(output, 0, bytesAfterdeflate); byte[] result = new byte[100]; int resultLength = decompresser.inflate(result); decompresser.end(); String outStr = new String(result, 0, resultLength, "UTF-8"); System.out.println("Decompressed data: "+outStr); } }
Compressed byte number:21 Decompressed data: Hellow World!