In this example, let’s see how to decompress byte array in Java.
Source Code
package com.beginner.examples;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class DecompressByte {
public static void main(String[] args) {
byte[] bytes = doCompressArray("Hello World".getBytes());
bytes = doDecompressByte(bytes);
System.out.println(new String(bytes));
}
/**
*
* @breif: java.util.zip package provides Inflater class to decompress byte array.
* @param: data
* @return
*/
public static byte[] doDecompressByte(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
GZIPInputStream gzip = new GZIPInputStream(bis);
byte[] buf = new byte[1024];
int num = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = gzip.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
b = baos.toByteArray();
baos.flush();
baos.close();
gzip.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
public static byte[] doCompressArray(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
gzip.close();
b = bos.toByteArray();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
}
Output:
Hello World
References
Imported packages in Java documentation: