To unzip files in Java you can use classes provided by java.util.zip
package for data compression and decompression.
Steps to unzip file in Java
To unzip a zipped file you need to read data from an input stream. For that you can use
ZipInputStream
class residing in the java.util.zip package.
Once ZIP input stream is opened, you can read the zip entries using the getNextEntry()
method which returns a
ZipEntry object
. If the end-of-file is reached, getNextEntry returns null.
While going through the zip entries you can check whether that entry is for a directory or for a file, if it is a directory just create the folder in destination. If it is a file then you need to read the data to the output file by opening an OutputStream.
Java program for unzipping file
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class Unzip { static final int BUFFER = 2048; // Output folder private static final String DEST_FOLDER = "G://Output"; public static void main (String argv[]) { try { File folder = new File(DEST_FOLDER); if(!folder.exists()){ folder.mkdir(); } BufferedOutputStream dest = null; // zipped input FileInputStream fis = new FileInputStream("G://files.zip"); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " +entry); int count; byte data[] = new byte[BUFFER]; String fileName = entry.getName(); File newFile = new File(folder + File.separator + fileName); // If directory then just create the directory (and parents if required) if(entry.isDirectory()){ if(!newFile.exists()){ newFile.mkdirs(); } }else{ // write the files to the disk FileOutputStream fos = new FileOutputStream(newFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zis.closeEntry(); } zis.close(); } catch(Exception e) { e.printStackTrace(); } } }
Note that though here output folder is taken as a separate folder with different name, but you can also derive that name using the input folder name.
- Refer Zipping files in Java to see example code how to derive output folder from the input folder.
That's all for this topic Unzip File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-