Java Unzip File
To unzip a zip file, we need to read the zip file with ZipInputStream
and then read all the ZipEntry
one by one. Then use FileOutputStream
to write them to file system.
We also need to create the output directory if it doesn’t exists and any nested directories present in the zip file.
Here is the java unzip file program that unzips the earlier created tmp.zip
to output directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.journaldev.files; 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 UnzipFiles { public static void main(String[] args) { String zipFilePath = "/Users/pankaj/tmp.zip"; String destDir = "/Users/pankaj/output"; unzip(zipFilePath, destDir); } private static void unzip(String zipFilePath, String destDir) { File dir = new File(destDir); // create output directory if it doesn't exist if(!dir.exists()) dir.mkdirs(); FileInputStream fis; //buffer for read and write data to file byte[] buffer = new byte[1024]; try { fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); while(ze != null){ String fileName = ze.getName(); File newFile = new File(destDir + File.separator + fileName); System.out.println("Unzipping to "+newFile.getAbsolutePath()); //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); //close this ZipEntry zis.closeEntry(); ze = zis.getNextEntry(); } //close last ZipEntry zis.closeEntry(); zis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } |
Once the program finishes, we have all the zip file contents in the output folder with same directory hierarchy.
Output of the above program is:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<span style="color: #008000;"><strong><code> Unzipping to /Users/pankaj/output/.DS_Store Unzipping to /Users/pankaj/output/data/data.dat Unzipping to /Users/pankaj/output/data/data.xml Unzipping to /Users/pankaj/output/data/xmls/project.xml Unzipping to /Users/pankaj/output/data/xmls/web.xml Unzipping to /Users/pankaj/output/data.Xml Unzipping to /Users/pankaj/output/DB.xml Unzipping to /Users/pankaj/output/item.XML Unzipping to /Users/pankaj/output/item.xsd Unzipping to /Users/pankaj/output/ms/data.txt Unzipping to /Users/pankaj/output/ms/project.doc </code></strong></span> |
That’s all about java unzip file example.