How to Compress Byte Array in Java


In this example, let’s see how to compress byte array in Java.

Source Code

package com.beginner.examples;

import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;

public class CompressArray {

	public static void main(String[] args) {
			
		byte[] bytes = doCompressArray("Hello World".getBytes());
		System.out.println(bytes);

	}
	
	/**
	 * @brief: java.util.zip package provides Deflater class to compress byte array.
	 * @param: data
	 * @return
	 */
	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;
	}

}

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments