File
Extract a compressed zip file
This is an example of how to extract a compressed zip file. Extracting a compressed zip file implies that you should:
- Create a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
- Create a new ZipInputStream.
- Create a new FileOutputStream using a path name to the file to write.
- Iterate over the ZipEntries of the ZipInputStream, using
getNextEntry()
method of ZipInputStream. - Read from the ZipInputStream, using its
read(byte[] b, int off, int len)
API method and write to the FileOutputStream withwrite(byte[] b, int off, int len)
API method.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ExtractZipFile { //Zipped file path e.g. C:/Users/nikos7/comperssed.zio private static final String zippedFilePath="<ZIPPED FILE PATH>"; private static final String outputFilePath="<OUTPUT FILE PATH>"; public static void main(String[] args) throws Exception { ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zippedFilePath)); OutputStream outputStream = new FileOutputStream(outputFilePath); byte[] buf = new byte[1024]; int read; ZipEntry zipEntry; if ((zipEntry = inputStream.getNextEntry()) != null) { while ((read = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, read); } } outputStream.close(); inputStream.close(); } }
This was an example of how to extract a compressed zip file in Java.