Unzipping Files with java.util.zip.ZipFile

Unzipping Files with java.util.zip.ZipFile

he Java core packages include jave.util.zip, which is useful forcreating and reading compressed files or archives in the ZIP and GZIPformats. ZIP files form the basis for the JAR file format, so it wasnatural to include classes for manipulating ZIP files as part of thestandard Java APIs. This functionality is enormously useful, becauseit saves you the time of creating custom file archive formats for yourapplications. You can use the ZipFile class to read entries ina ZIP file. The entries are represented by instances of the ZipEntryclass, which contains information such as the size, name, compressionmethod, and timestamp of the entry. ZipFile.entries() will return theentries as an Enumeration which you can step through to access all ofthe entries. Once you have found an entry of interest,ZipFile.getInputStream(ZipEntry) will produce an InputStream, fromwhich the archived entry can be read.

The following program demonstrates how to use the ZipFile class tocreate a simple unzip utility. It simply cycles through all of theentries in the file and copies each entry to a new file by reading itsinput stream. If an entry is a directory, it is created. The exampleis not robust and is only intended to demonstrate the ZipFile class.Obvious additions would include checking if a file already exists beforecreating it, prompting the user if it should be overwritten, as wellas other error checking. View the example>:

import java.io.*;import java.util.*;import java.util.zip.*;public class Unzip {  public static final void copyInputStream(InputStream in, OutputStream out)  throws IOException  {    byte[] buffer = new byte[1024];    int len;    while((len = in.read(buffer)) >= 0)      out.write(buffer, 0, len);    in.close();    out.close();  }  public static final void main(String[] args) {    Enumeration entries;    ZipFile zipFile;    if(args.length != 1) {      System.err.println("Usage: Unzip zipfile");      return;    }    try {      zipFile = new ZipFile(args[0]);      entries = zipFile.entries();      while(entries.hasMoreElements()) {        ZipEntry entry = (ZipEntry)entries.nextElement();        if(entry.isDirectory()) {          // Assume directories are stored parents first then children.          System.err.println("Extracting directory: " + entry.getName());          // This is not robust, just for demonstration purposes.          (new File(entry.getName())).mkdir();          continue;        }        System.err.println("Extracting file: " + entry.getName());        copyInputStream(zipFile.getInputStream(entry),           new BufferedOutputStream(new FileOutputStream(entry.getName())));      }      zipFile.close();    } catch (IOException ioe) {      System.err.println("Unhandled exception:");      ioe.printStackTrace();      return;    }  }}
Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as