How to Unzip a Zip File in Java
The Java programming language was developed for easy cross-platform programming. With Java, a programmer can write a single application and run it, with little to no modification, on almost any operating system. One of the features built directly into Java is the ability to read and write ZIP archive files using the ZipEntry and ZipFile classes. The ZipFile class provides a collection of ZipEntries, and each ZipEntry provides a standard stream that can be read with any of Java's built-in Stream classes, including the easy-to-use Scanner class.
Instructions
-
-
1
Open Netbeans. These instructions will assume you use the NetBeans Integrated Development Environment (IDE) that comes free with Sun Microsystems' version of Java, but they will work with any plain text editor with a minimum of modification.
-
2
Create a new project named "ZipExample" by clicking "File," "New Project." This will automatically set up a default class file for you named Main that already has a valid 'main' method and open it.
-
-
3
Paste the following at the top of the file, above the line that reads "public class Main" and below the line "package zipexample."
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
-
4
Paste the following within the main method:
public static void main(String[] args) {
// Get the file name of a zip file from the command line.
// Alternatively, write your own file name here.
String filename = args[0];
try {
// Open the zip file.
ZipFile archive = new ZipFile(filename);
Enumeration<? extends ZipEntry> fileList = archive.entries();
// Go through each file in the ZIP archive.
for (ZipEntry e = fileList.nextElement();
fileList.hasMoreElements();
e = fileList.nextElement()) {
// Print some info to let the user know what is happening.
System.out.println("Expanding " + e.getName());
// If the zip entry is a directory, make the directory.
if (e.isDirectory()) new File(e.getName()).mkdir();
else {
// If it's not a directory, read the data from
// the zip archive and write it to the disk.
InputStream in = archive.getInputStream(e);
Scanner scan = new Scanner(in);
FileOutputStream fout = new FileOutputStream(e.getName());
while (scan.hasNextByte()) {
fout.write(scan.nextByte());
}
// Close the file.
fout.close();
}
}
}catch (IOException e) {
// If there is any sort of error reading or writing, print
// an error message to the console.
System.out.println(e.getMessage());
}
}
-
5
Click the green arrow to run the program.
-
1