- Java IO Tutorial — Java Zip Byte Array
- Compressing Byte Arrays
- How to zip file from byte[] array in In Java?
- Method 1: Using the java.util.zip Package
- Method 2: Using the Apache Commons Compress Library
- Method 3: Using the Java 7 NIO Package
- 360learntocode
- How to Compress(Zip) and Decompress(Unzip) byte array in Java
- Program: How to compress byte array in java?
- List of all java.util.zip class sample examples:
- About Author
- Most Visited Pages
Java IO Tutorial — Java Zip Byte Array
Java provides an Adler32 class in the java.util.zip package to compute the Adler-32 checksum for bytes of data.
We need to call the update() method of this class to pass bytes to it.
There is also another class named CRC32 in the same package, which lets you compute a checksum using the CRC32 algorithm.
The following code illustrates how to use the Adler32 and CRC32 classes to compute checksums.
import java.util.zip.Adler32; import java.util.zip.CRC32; // w ww . ja v a 2s. c o m public class Main < public static void main(String[] args) throws Exception < String str = "HELLO"; byte[] data = str.getBytes("UTF-8"); System.out.println("Adler32 and CRC32 checksums for " + str); // Compute Adler32 checksum Adler32 ad = new Adler32(); ad.update(data); long adler32Checksum = ad.getValue(); System.out.println("Adler32: " + adler32Checksum); // Compute CRC32 checksum CRC32 crc = new CRC32(); crc.update(data); long crc32Checksum = crc.getValue(); System.out.println("CRC32: " + crc32Checksum); > >
The code above generates the following result.
Compressing Byte Arrays
We can use the Deflater and Inflater classes in the java.util.zip package to compress and decompress data in a byte array, respectively.
We can specify the compression level using one of the constants in the Deflater class.
Those constant are BEST_COMPRESSION, BEST_ SPEED, DEFAULT_COMPRESSION, and NO_COMPRESSION.
The best speed means lower compression ratio and the best compression means slower compression speed.
Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION);
By default, the compressed data using the Deflater object will be in the ZLIB format.
To compress data in GZIP or PKZIP format, specify that by using the boolean flag as true in the constructor.
// Uses the best speed compression and GZIP format Deflater compressor = new Deflater(Deflater.BEST_SPEED, true);
The following code shows how to do Compressing and Decompressing a byte Array Using Deflater and the Inflater classes
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; //from w w w . j av a 2s. com public class Main < public static void main(String[] args) throws Exception < String input = "Hello world!"; byte[] uncompressedData = input.getBytes("UTF-8"); byte[] compressedData = compress(uncompressedData, Deflater.BEST_COMPRESSION, false); byte[] decompressedData = decompress(compressedData, false); String output = new String(decompressedData, "UTF-8"); System.out.println("Uncompressed data length: " + uncompressedData.length); System.out.println("Compressed data length: " + compressedData.length); System.out.println("Decompressed data length: " + decompressedData.length); > public static byte[] compress(byte[] input, int compressionLevel, boolean GZIPFormat) throws IOException < Deflater compressor = new Deflater(compressionLevel, GZIPFormat); compressor.setInput(input); compressor.finish(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] readBuffer = new byte[1024]; int readCount = 0; while (!compressor.finished()) < readCount = compressor.deflate(readBuffer); if (readCount > 0) < bao.write(readBuffer, 0, readCount); >> compressor.end(); return bao.toByteArray(); > public static byte[] decompress(byte[] input, boolean GZIPFormat) throws IOException, DataFormatException < Inflater decompressor = new Inflater(GZIPFormat); decompressor.setInput(input); ByteArrayOutputStream bao = new ByteArrayOutputStream(); byte[] readBuffer = new byte[1024]; int readCount = 0; while (!decompressor.finished()) < readCount = decompressor.inflate(readBuffer); if (readCount > 0) < bao.write(readBuffer, 0, readCount); >> decompressor.end(); return bao.toByteArray(); > >
The code above generates the following result.
java2s.com | © Demo Source and Support. All rights reserved.
How to zip file from byte[] array in In Java?
When working with file inputs in a Java application, you may need to convert a byte array into a zipped file. This can be useful when you want to send multiple files in a compact format or when you need to store a large number of files in a smaller space. Zipping a file in Java can be achieved using several libraries and APIs, and in this article, we will explore the most common methods of zipping a file from a byte array.
Method 1: Using the java.util.zip Package
To zip a file from a byte array in Java using the java.util.zip package, you can follow these steps:
- Create a ByteArrayInputStream object from the byte array.
- Create a ZipOutputStream object and pass a FileOutputStream object to it.
- Create a ZipEntry object and set its name to the desired name of the zipped file.
- Write the contents of the ByteArrayInputStream object to the ZipOutputStream object using the putNextEntry method.
- Close the ZipEntry and ZipOutputStream objects.
Here is an example code snippet that demonstrates the above steps:
import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipExample public static void main(String[] args) throws Exception byte[] data = "Hello, World!".getBytes(); String filename = "example.zip"; try (ByteArrayInputStream bais = new ByteArrayInputStream(data); FileOutputStream fos = new FileOutputStream(filename); ZipOutputStream zos = new ZipOutputStream(fos)) ZipEntry entry = new ZipEntry("example.txt"); zos.putNextEntry(entry); byte[] buffer = new byte[1024]; int len; while ((len = bais.read(buffer)) > 0) zos.write(buffer, 0, len); > zos.closeEntry(); > > >
In this example, we first create a byte array data containing the contents of the file we want to zip. We also specify a filename for the zipped file.
We then create a ByteArrayInputStream object from the data byte array, and a FileOutputStream object from the filename .
Next, we create a ZipOutputStream object from the FileOutputStream object, and a ZipEntry object with the name «example.txt».
We then write the contents of the ByteArrayInputStream object to the ZipOutputStream object using a buffer, and close the ZipEntry and ZipOutputStream objects.
Finally, we have a zipped file named example.zip containing a file named example.txt with the contents «Hello, World!».
Method 2: Using the Apache Commons Compress Library
Here’s how to zip a file from a byte array in Java using the Apache Commons Compress library:
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-compressartifactId> version>1.21version> dependency>
byte[] fileData = // read file data into byte array
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream);
ZipArchiveEntry zipEntry = new ZipArchiveEntry("filename.txt"); zipOutputStream.putArchiveEntry(zipEntry); zipOutputStream.write(fileData); zipOutputStream.closeArchiveEntry();
- Finally, close the ZipArchiveOutputStream and get the compressed data from the ByteArrayOutputStream:
zipOutputStream.finish(); byte[] compressedData = outputStream.toByteArray();
That’s it! You’ve successfully zipped a file from a byte array using the Apache Commons Compress library.
Method 3: Using the Java 7 NIO Package
Here are the steps to zip a file from a byte[] array using Java 7 NIO Package:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(byteArray);
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArrayOutputStream.toByteArray());
Path path = Paths.get("output.zip");
URI uri = URI.create("jar:file:" + path.toUri().getPath()); MapString, String> env = new HashMap>(); env.put("create", "true"); FileSystem zipFileSystem = FileSystems.newFileSystem(uri, env);
Path fileToZip = zipFileSystem.getPath("file.txt");
Files.write(fileToZip, byteBuffer.array(), StandardOpenOption.CREATE);
Here is the complete code example:
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.*; import java.util.HashMap; import java.util.Map; public class ZipFileFromByteArray public static void main(String[] args) throws IOException // byte[] array byte[] byteArray = "This is a test file".getBytes(); // Create a ByteArrayOutputStream object to write the bytes to be zipped ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Write the byte[] array to the ByteArrayOutputStream object byteArrayOutputStream.write(byteArray); // Create a ByteBuffer object from the ByteArrayOutputStream object ByteBuffer byteBuffer = ByteBuffer.wrap(byteArrayOutputStream.toByteArray()); // Create a Path object for the output zip file Path path = Paths.get("output.zip"); // Create a FileSystem object for the zip file URI uri = URI.create("jar:file:" + path.toUri().getPath()); MapString, String> env = new HashMap>(); env.put("create", "true"); FileSystem zipFileSystem = FileSystems.newFileSystem(uri, env); // Create a Path object for the file to be zipped inside the zip file Path fileToZip = zipFileSystem.getPath("file.txt"); // Write the ByteBuffer object to the file inside the zip file Files.write(fileToZip, byteBuffer.array(), StandardOpenOption.CREATE); // Close the zip file system zipFileSystem.close(); > >
360learntocode
How to Compress(Zip) and Decompress(Unzip) byte array in Java
In this tutorial, we are going to compress and decompress the bytes array. The process may be required when serializing data as a binary file especially when the bytes array has non-unique data.
Let’s create the method that compresses the bytes array.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.DeflaterOutputStream; public static byte[] compress(byte[] bytes) throws IOException
This method will compress the bytes array. If this results in no reduction in length then the data might be unique or tend to be unique. If the data is truly unique random values then the compression might produce the greater length as well. Compression always has overhead to allow for future decompression.
import java.util.zip.InflaterInputStream; import java.io.ByteArrayInputStream; public static byte[] decompress(byte[] bytes) throws IOException < ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArrayInputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int read; while ((read = inflaterInputStream.read()) != -1) < byteArrayOutputStream.write(read); >inflaterInputStream.close(); byteArrayInputStream.close(); byteArrayOutputStream.close(); return byteArrayOutputStream.toByteArray(); >
public static void main(String[] args) < byte[] b = new byte[10000]; // bytes data with 0 values System.out.println("Initial Data Size : "+ b.length); try < byte[] compressedBytes = compress(b); System.out.println("Compressed Data Size : "+ compressedBytes.length); byte[] decompressedBytes = decompress(compressedBytes); System.out.println("Decompressed Data Size: "+ decompressedBytes.length); >catch (IOException e) < System.out.println("Error while zipping due to : "+e.getMessage()); >>
Initial Data Size : 10000 Compressed Data Size : 33 Decompressed Data Size: 10000
There is an options to add different algorithm while doing compression using Deflater class as below
import java.util.zip.Deflater; public static byte[] compress(byte[] bytes) throws IOException
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import java.io.ByteArrayInputStream; public class Zip < public static void main(String[] args) < byte[] b = new byte[10000]; // bytes data with 0 values System.out.println("Initial Data Size : " + b.length); try < byte[] compressedBytes = compress(b); System.out.println("Compressed Data Size : " + compressedBytes.length); byte[] decompressedBytes = decompress(compressedBytes); System.out.println("Decompressed Data Size: " + decompressedBytes.length); >catch (IOException e) < System.out.println("Error while zipping due to : " + e.getMessage()); >> public static byte[] compress(byte[] bytes) throws IOException < ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream); deflaterOutputStream.write(bytes); deflaterOutputStream.close(); byte[] compressedBytes = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); return compressedBytes; >public static byte[] decompress(byte[] bytes) throws IOException < ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArrayInputStream); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int read; while ((read = inflaterInputStream.read()) != -1) < byteArrayOutputStream.write(read); >inflaterInputStream.close(); byteArrayInputStream.close(); byteArrayOutputStream.close(); return byteArrayOutputStream.toByteArray(); > >
Program: How to compress byte array in java?
java.util.zip package provides Deflater class to compress byte array. The sample code to compress a byte array is given in the below example.
package com.java2novice.zip; import java.io.ByteArrayOutputStream; import java.util.zip.Deflater; public class MyByteArrayCompress < public byte[] compressByteArray(byte[] bytes)< ByteArrayOutputStream baos = null; Deflater dfl = new Deflater(); dfl.setLevel(Deflater.BEST_COMPRESSION); dfl.setInput(bytes); dfl.finish(); baos = new ByteArrayOutputStream(); byte[] tmp = new byte[4*1024]; try< while(!dfl.finished())< int size = dfl.deflate(tmp); baos.write(tmp, 0, size); >> catch (Exception ex) < >finally < try< if(baos != null) baos.close(); >catch(Exception ex)<> > return baos.toByteArray(); > public static void main(String a[]) < MyByteArrayCompress mbc = new MyByteArrayCompress(); byte[] content = mbc.compressByteArray("Compress java2novice.com".getBytes()); System.out.println(new String(content)); >>
List of all java.util.zip class sample examples:
- How to compress byte array in java?
- How to decompress byte array in java?
- How to zip a single file?
- How to zip multiple files?
- How to read zip files entries or file name list?
- How to unzip files in java?
- How to generate checksum value for for a file in java?
- How to compress and store objects using zip utility?
- How to decompress the compressed objects using zip utility?
- How to zip a file using ZipFile class?
- How to compress a file in GZip format?
- How to uncompress a file from GZip format?
In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.
In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
About Author
I’m Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.
If you come across any mistakes or bugs, please email me to [email protected] .