Given a byte array of compressed data, return a byte array of uncompressed data. - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Given a byte array of compressed data, return a byte array of uncompressed data.

Demo Code


//package com.java2s;

import java.util.zip.*;
import java.io.*;

public class Main {
    /**// w  w  w  . j  a va2  s .  c  o m
     * Given a byte array of compressed data, return a byte array of uncompressed data.
     * Uses java.util.zip (zlib) compression.
     * 
     * @param compressedData the compressed byte array
     * @return the uncompressed byte array
     * @throws IOException if data can't be decompressed
     */
    public static byte[] decompress(byte[] compressedData)
            throws IOException {
        Inflater decompressor = new Inflater();
        decompressor.setInput(compressedData);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(
                compressedData.length);
        byte[] buf = new byte[1024];
        while (!decompressor.finished()) {
            try {
                int count = decompressor.inflate(buf);
                bos.write(buf, 0, count);
            } catch (DataFormatException e) {
                throw new IOException("Data can't be decompressed");
            }
        }
        try {
            bos.close();
        } catch (IOException e) {
        }
        byte[] decompressedData = bos.toByteArray();
        return decompressedData;
    }
}

Related Tutorials