How to Unzip a File in Java? - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

How to Unzip a File in Java?

Share This

Following Code Snippet decompresses a zipped file to a target directory. The class name is unZipper and takes the zipped file's absolute path and the target directory path as input. The class is tested with the main method inside the class body itself.

This class utilizes java.util.zip and the code is commented for easy understanding.

The flow of the code is like
  • Access the output directory, if not created earlier, create it
  • Get the file input stream out of the input zipped file
  • Get the zip input stream out of the file input stream
  • Get the zip entry out of the zip input stream
  • For all zip entries
  • Create the sub-directory of the current recursive files within the input directory
  • Create the file output stream of the current file
  • Read from the zip input stream and write to the current file
  • Close all the resources
Here goes the code
package com.t4b.util.zip.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class TestMain { private String zipFile; private String extractFilePath; public TestMain(String zipFile, String extractFilePath) { this.zipFile = zipFile; this.extractFilePath = extractFilePath; } public void unZip() { byte[] buffer = new byte[1024]; try { File targetDir = new File(extractFilePath); if (!targetDir.exists()) { targetDir.mkdir(); } FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(fis); ZipEntry zEntry = zis.getNextEntry(); while (zEntry != null) { String fileName = zEntry.getName(); File fileToBeCreated = new File(extractFilePath + File.separator + fileName); new File(fileToBeCreated.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(fileToBeCreated); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); zEntry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); System.out.println(extractFilePath + " is ready "); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { TestMain unZip = new TestMain("test.zip", "testdir"); unZip.unZip(); } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.