Home » Core Java » util » zip » Compress – Decompress files example

About Byron Kiourtzoglou

Avatar photo
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Compress – Decompress files example

This is an example of how to zip and unzip a file. We have implemented the FileCompressionUtil class, that consists of four methods, that zip and unzip a file with or without a checksum.

    The first method zipFilesInPath(final String zipFileName, final String filePath) zips a file in a specific path.

  • The method creates a ZipOutputStream, using a FileOutputStream, with the given zipFilename.
  • It creates a new File with the given file path.
  • It takes an array of strings naming the files and directories in the directory, using the list() API method of File, and puts them in a List of Strings, using the asList(String... a) API method of the Arrays Class.
  • For each one of the files in the list it creates a BufferedInputStream using a FileInputStream and a specified buffer size.
  • The zipOutputStream begins writing a new ZipEntry, using putNextEntry(ZipEntry e) API method and as parameter a new ZipEntry created for the specified file.
  • While the BufferedInputStream reads bytes from the file, into a specified byte array, with read(byte[] b, int off, int len) API method, the ZipoutputStream writes it to the specified ZipEntry, with write(byte[] b, int off, int len) API method.
  • Finally, the all input and output streams close, using their close() API methods.
    The second method zipFilesInPathWithChecksum(final String zipFileName, final String folderPath) zips a file in a specific path, using a checksum.

  • It follows the same steps as the first one, but it also uses a CheckedOutputStream with the intitial FileOutputStream and a new CRC32 Checksum, in order to create the ZipOutputStream that will write to the zip file.
  • The method returns the value of the new checksum, using getCheckSum() API method of CheckedOutputStream and then getValue() API method of Checksum.
    The third method unzipFilesToPath(final String zipFileName, final String fileExtractPath) unzips files to a specified path. It creates a ZipInputStream, using a FileInputStream for the given zipfilename.

  • It reads each ZipEntry object of the ZipInputStream, with getNextEntry() API method of ZipInputStream and for each ZipEntry it creates a BufferedOutputStream, using a FileOutputStream with the path of the extracted file.
  • While the ZipInputStream reads from the current ZIP entry into an array of bytes the BufferedOutputStream writes the byte array.
  • When finished, the BufferedOutputStream flushes, with its flush() API method and finally all input and output streams close, using their close() API methods.
    The last method unzipFilesToPathWithChecksum(final String zipFileName, final String fileExtractPath, final long checksum) unzips files to a specified path, using a checksum.
  • It follows the same steps as the previous one, but it also creates a CheckedInputStream with the intitial FileInputStream and a new CRC32 Checksum, in order to create the ZipInputStream that will read from the zip file.
  • It returns true if the checksum of the CheckedInputStream is the same as the checksum given as parameter to the method.

Let’s take a look at the code snippet that follows:

package javaitzen.blog;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
 
/**
 * The Class FileCompressionUtil.
 */
public class FileCompressionUtil {
 
 private static final String PATH_SEP = "\";
 public static final int BUFFER = 2048;
 private FileCompressionUtil() {}
  
 /**
  * Zip files in path.
  * 
  * @param zipFileName the zip file name
  * @param filePath the file path
  * @throws IOException Signals that an I/O exception has occurred.
  */
 public static void zipFilesInPath(final String zipFileName, final String filePath) throws IOException {
  final FileOutputStream dest = new FileOutputStream(zipFileName);
  final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
  try {
 
   byte[] data = new byte[BUFFER];
   final File folder = new File(filePath);
   final List< String > files = Arrays.asList(folder.list());
   for (String file : files) {
    final FileInputStream fi = new FileInputStream(filePath + PATH_SEP + file);
    final BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
    out.putNextEntry(new ZipEntry(file));
    int count;
    while ((count = origin.read(data, 0, BUFFER)) != -1) {
     out.write(data, 0, count);
    }
    origin.close();
    fi.close();
   }
  } finally {
   out.close();
   dest.close();
  }
 }
 
 /**
  * Zip with checksum. CRC32
  * 
  * @param zipFileName the zip file name
  * @param folderPath the folder path
  * @return the checksum
  * @throws IOException Signals that an I/O exception has occurred.
  */
 public static long zipFilesInPathWithChecksum(final String zipFileName, final String folderPath) throws IOException {
 
  final FileOutputStream dest = new FileOutputStream(zipFileName);
  final CheckedOutputStream checkStream = new CheckedOutputStream(dest, new CRC32());
  final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checkStream));
  try {
   byte[] data = new byte[BUFFER];
   final File folder = new File(folderPath);
   final List< String > files = Arrays.asList(folder.list());
   for (String file : files) {
    final FileInputStream fi = new FileInputStream(folderPath + PATH_SEP + file);
    final BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
    out.putNextEntry(new ZipEntry(file));
    int count;
    while ((count = origin.read(data, 0, BUFFER)) != -1) {
     out.write(data, 0, count);
    }
    origin.close();
   }
   
  } finally {
   out.close();
   checkStream.close();
   dest.flush();
   dest.close();
  }
 
  return checkStream.getChecksum().getValue();
 }
 
 
 /**
  * Unzip files to path.
  * 
  * @param zipFileName the zip file name
  * @param fileExtractPath the file extract path
  * @throws IOException Signals that an I/O exception has occurred.
  */
 public static void unzipFilesToPath(final String zipFileName, final String fileExtractPath) throws IOException {
 
  final FileInputStream fis = new FileInputStream(zipFileName);
  final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
  try {
   ZipEntry entry;
 
   while ((entry = zis.getNextEntry()) != null) {
    int count;
    byte[] data = new byte[BUFFER];
    final FileOutputStream fos = new FileOutputStream(fileExtractPath + PATH_SEP + entry.getName());
    final BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
    while ((count = zis.read(data, 0, BUFFER)) != -1) {
     dest.write(data, 0, count);
    }
    dest.flush();
    dest.close();
   }
  } finally {
   fis.close();
   zis.close();
  }
 
 }
 
 
 /**
  * Unzip files to path with checksum. CRC32
  * 
  * @param zipFileName the zip file name
  * @param fileExtractPath the file extract path
  * @param checksum the checksum
  * @return true, if checksum matches;
  * @throws IOException Signals that an I/O exception has occurred.
  */
 public static boolean unzipFilesToPathWithChecksum(final String zipFileName, final String fileExtractPath, final long checksum) throws IOException {
 
  boolean checksumMatches = false;
  final FileInputStream fis = new FileInputStream(zipFileName);
  final CheckedInputStream checkStream = new CheckedInputStream(fis, new CRC32());
  final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checkStream));
 
  try {
 
   ZipEntry entry = null;
   while ((entry = zis.getNextEntry()) != null) {
    int count;
    byte[] data = new byte[BUFFER];
    final FileOutputStream fos = new FileOutputStream(fileExtractPath + PATH_SEP + entry.getName());
    final BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
    while ((count = zis.read(data, 0, BUFFER)) != -1) {
     dest.write(data, 0, count);
    }
    dest.flush();
    dest.close();
   }
 
  } finally {
   zis.close();
   fis.close();
   checkStream.close();
  }
 
  if(checkStream.getChecksum().getValue() == checksum) {
   checksumMatches = true;
  }
   
  return checksumMatches;
 }
 
}

 
This was an example of how to zip and unzip a file in Java.
 

Related Article:

Reference: Java Compression from our JCG partner Brian at Zen in the art of IT

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments