February 5, 2024

How to Unzip a File in Java

When you zip a file in Java there are different logic based on whether you are zipping a file or you are zipping a folder in Java where the whole directory structure is archived. But unzipping a file in Java doesn’t need such different functionalities. One Java program to unzip a file takes care of all the different functionalities.

Unzip a file – Java program

To unzip a file you need to follow the following steps-

  • Read the compressed file from the zipped archive. For that java.util.zip.ZipInputStream class is used.
  • From the ZipInputStream, zip entries for the files and directories are read using getNextEntry() method.
  • If the entry is for a directory then you just need to create the directory. If the entry is for file then read the content of the file and write it to the destination file.
  • Close the current entry using the closeEntry() method.
  • Once all the zip entries are iterated close the input and output streams.
public class UnzipFile {
  private static final int BUFFER = 2048;
  public static void main(String[] args) {
    final String SOURCE_ZIPDIR = "F:/knpcode/Parent.zip";
    // creating the destination dir using the zip file path
    // by truncating the ".zip" part
    String DESTINATION_DIR = SOURCE_ZIPDIR.substring(0, SOURCE_ZIPDIR.lastIndexOf('.'));
    //System.out.println("" + DESTINATION_DIR);
    extract(SOURCE_ZIPDIR, DESTINATION_DIR);
  }
	
  private static void extract(String source, String dest){
    try {
      File root = new File(dest);
      if(!root.exists()){
        root.mkdir();
      }
      BufferedOutputStream bos = null;
      // zipped input
      FileInputStream fis = new FileInputStream(source);
      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
      ZipEntry entry;
      while((entry = zis.getNextEntry()) != null) {
        String fileName = entry.getName();
        File file = new File(dest + File.separator + fileName);
        if (!entry.isDirectory()) {
          extractFileContentFromArchive(file, zis);
        }
        else{
          if(!file.exists()){
            file.mkdirs();
          }
        }
        zis.closeEntry();
      }
      zis.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
	
  private static void extractFileContentFromArchive(File file, ZipInputStream zis) throws IOException{
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
    int len = 0;
    byte data[] = new byte[BUFFER];
    while ((len = zis.read(data, 0, BUFFER)) != -1) {
      bos.write(data, 0, len);
    }
    bos.flush();
    bos.close();
  }
}

That's all for the topic How to Unzip a File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment