How to Read Zip Files With Java
You may not realize it, but Java already has all the tools it needs to handle the common file compression and packaging ZIP format built right in by default. If you need to write an application that is able to handle ZIP files, such as a new WinZip killer, Java has all the equipment you need to get started.
Instructions
-
-
1
Create a Java program. At the most simple, you can do this by opening any text editor, such as Notepad, and immediately saving it with the name "ZipReader.java." However, if you have a Java Integrated Development Environment like Netbeans or Eclipse, you can save a little time by clicking "File"-->"New Project."
-
2
Import the following libraries from the Java standard library that you will need to read Zip files by pasting the following at the top of the file you just created in step 1.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-
-
3
Paste the following code into the program to give it its basic structure:
public class ZipExample {
public static void main(String[] args) {
try {
} catch (Exception e) {
System.out.println("ERROR");
}
}
}
All the rest of the code will go between the "try" and "catch" statements, which are designed to handle any errors that may occur.
-
4
Prepare some variables to hold the data from the zip file temporarily by pasting the following commands into the "try" block of the main method you wrote in step 3:
ZipEntry entry;
int BUFFER = 1024;
int count = 0;
byte[] data = new byte[1024];
ZipEntry will refer to each file in the ZIP archive in turn. Buffer is the number of bytes to read from the ZIP file at a time, and 1,024 is a fairly standard number, but it does not matter what you choose. The purpose is simply to insure that the hard disk is not overworked reading individual bytes one by one. Finally, count is going to keep track of how many bytes are actually read from the ZIP file in each pass (since it the file size is unlikely to be a multiple of 1024.) This is important, because you will need to know how much data is being written to the new file in step 6.
-
5
Open the ZIP file. This is a two-step process. First, you must read the zip file into a FileInputStream, and second you must convert this into a ZipInputStream. Paste the following code to accomplish this:
FileInputStream file_input = new FileInputStream("archive.zip");
ZipInputStream zin = new ZipInputStream(file_input);
-
6
Go through the ZIP file, one entry at a time and write that entry to the hard drive, with the following code, pasted immediately after the last code:
while ((entry = zin.getNextEntry()) != null) {
FileOutputStream fout = new FileOutputStream(entry.getName());
while ((count = zin.read(data, 0, BUFFER)) != -1) {
fout.write(data, 0, count);
}
fout.flush();
fout.close();
}
-
7
Close the ZIP file by pasting the following immediately after the last code:
zin.close();
-
1