The sole purpose
of this program is how to extarct the content of a zip file in java.We
start by opening an input stream to the compressed file and an output
stream to the file where we want the content to be extracted.
After that we get
the next entry of the zip file (and the only entry in this case) -
test so it's not null, and then start reading the contents from the
input stream and writing each chunk read to the output stream.
As usual we should
clean up properly afterwards so we close the input and output
streams.
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; public class ExtractingZipFile{ /** * Extracts a zip file */ public void extractZipFile() { try { String zipFileName = "file.zip"; String extractedFileName = "extractedfile.txt"; //Create input and output streams ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName)); OutputStream outStream = new FileOutputStream(extractedFileName); ZipEntry entry; byte[] buffer = new byte[1024]; int nrBytesRead; //Get next zip entry and start reading data if ((entry = inStream.getNextEntry()) != null) { while ((nrBytesRead = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, nrBytesRead); } } //Finish off by closing the streams outStream.close(); inStream.close(); } catch (IOException ex) { ex.printStackTrace(); } } /** * @param args the command line arguments */ public static void main(String[] args) { new ExtractingZipFile().extractZipFile(); } }