Example of Deflater and Inflater in Java

By Arvind Rai, November 13, 2023
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 a string to compress and then we have decompressed the compressed string.

Example

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);
  }
}
Output
Compressed byte number:21
Decompressed data: Hellow World! 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us