How to Extract Zip Files in Java
- 1). Import the IO classes at the beginning of the Java file. Without the zip file library, Java triggers an error. The following code imports the essential libraries for file manipulation:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; - 2). Set the location of the zip file archive and the location where the program will extract the file. The following code saves each location in a string variable for later use in the code:
String myZip= "C:\\zipfile.zip";
String extractLocation= "c:\\myextract.txt"; - 3). Allocate input and output streams to access the files. These streams are necessary for Java to read and write to files. The following code creates these variables with the string location indicated in step two. The buffer is used to load the entries into memory for faster processing:
ZipInputStream myIn= new ZipInputStream(new FileInputStream(myZip));
OutputStream myOut= new FileOutputStream(extractLocation);
ZipEntry zipVar;
byte[] mybuf= new byte[1024];
int readbyte; - 4). Extract the file. This example only sets up one file, but the following example checks for multiple file entries:
if ((zipVar = myIn.getNextEntry()) != null) {
while ((readbyte= myIn.read(mybuf)) > 0) {
myOut.write(mybuf, 0, readbyte);
}
} - 5). Close the streams to free resources on the host computer:
myOut.close();
myIn.close();
Source...