Zip files are compressed files that is used for transferring files over the internet. Zip and unzip are very important operations while writing application programs. Java provides a rich API to zip and unzip the files. By using ZIP API in java we can zip and unzip into standards ZIP and GZIP formats.
As always we will be discussing constructors than moving onto methods furthermore implementing the ZIp API. Let us start off with the constructors as follows:
1. Default constructor: Zip entry with the specified name gets created and it takes string name as an argument.
ZipEntry() {}
2. Parameterized constructor: New zip entry gets created by using the specified file
2.1 ZipEntry e
ZipEntry(e) {}
2.2 File file: For opening and reading ZIP files for a specified file object
ZipFile(File) {}
2.3 For opening and reading ZIP files for a specified file object
ZipFile(File file, Charset charset) {{}
Now let us do discuss methods which are as follows:
Method 1: getEntry(): Tells zip file entry for the specified name, or null if not found.
Syntax:
getEntry()
Return type: ZipEntry
Parameters: String name
Method 2: getInputStream(): Â Used to get the input stream for reading the contents of specified zip entries.
Syntax:
getNextEntry()
Return type : InputStream
parameters: ZipEntry zipEntry
Method 3: putNextentry(): Starts writing a new ZIP file entry. Then it positions the stream to the start of entry data.
Syntax:
putNextentry() {}
Return Type: Void
Parameters: ZipEntry e
Implementation:
Example 1
Java
// Java Program to Illustrate ZIP API// To Zip a FileÂ
// Importing required classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;Â
// Class 1// GfgZipDemopublic class GFG {Â
    // Main driver method    public static void main(String[] argv)    {Â
        // Calling method 2 inside main()        GfgZipDemo.zip_one_file();    }Â
    // Method 2    // To perform ZIP on files    public static void zip_one_file()    {Â
        // Creating a byte array        byte[] buffer = new byte[1024];Â
        // Try block to check for exceptions        try {Â
            // Creating outputstream for writing the            // information For ex c:\\desktop            FileOutputStream fos = new FileOutputStream(                "DESTINATION_PATH_WHERE_YOU_WANT_YOUR_ZIP");Â
            // Creating zip outputstream for zipping the            // file by creating objects of ZipEntry and            // ZipOutputStream classes            ZipOutputStream zos = new ZipOutputStream(fos);            ZipEntry ze = new ZipEntry("testing1.txt");Â
            zos.putNextEntry(ze);Â
            // For ex c:\\desktop\\abc.txt            FileInputStream in                = new FileInputStream("FILE_TO_ZIP_PATH");Â
            // Looping            int lengths;            // Holds true till there is something in byte            // array as declared above of size 1024            while ((lengths = in.read(buffer)) > 0) {Â
                // Write                zos.write(buffer, 0, lengths);            }Â
            // Closing file connections using close() method            // Closing entries using closeEntry() method            in.close();            zos.closeEntry();            zos.close();Â
            // Print message on console to illustrate            // successful execution of program            System.out.println("Successfully compiled and executed.");        }Â
        // Catch block to handle exceptions        catch (IOException ex) {Â
            // Display the exceptions along with line number            // using printStackTrace() method            ex.printStackTrace();        }    }} |
Output: On console generated after entering your path you will get the following outputÂ
Successfully compiled and executed.
It can be perceived from the image where the file is generated as shown in the below media as follows:
Â
Example 2Â
Java
// Java Program to Illustrate ZIP API// Where we are Unzipping a FileÂ
// Importing required classesimport java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.List;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;Â
// Main class// GfgUnZipDemopublic class GFG {Â
    // Member variables of class    List fileList;    private static final String INPUT_ZIP_FILE        = "YOUR_ZIP_FILE_PATH";    // For ex c:\\desktop\\abc.zip    private static final String OUTPUT_FOLDER        = "YOUR_UNZIPPED_ZIP_FILE_PATH";    // For ex c:\\desktopÂ
    // Main driver method    public static void main(String[] args)    {        // Creating object of class inside main()        GFG unZip = new GFG();        unZip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);    }Â
    // Method 2    // To unzip a file    public void unZipIt(String zipFile, String outputFolder)    {Â
        // Creating a byte array        byte[] buffer = new byte[1024];Â
        // Try block to check for exceptions        try {Â
            // Creating output directory            File folder = new File(OUTPUT_FOLDER);Â
            // If there is a folder            if (!folder.exists()) {                folder.mkdir();            }Â
            // Than get the zip file            ZipInputStream zis = new ZipInputStream(                new FileInputStream(zipFile));Â
            // Getting the zipped list entry            ZipEntry ze = zis.getNextEntry();Â
            // Till file is not fully unzipped            while (ze != null) {Â
                String fileName = ze.getName();                File newFile                    = new File(outputFolder + File.separator                               + fileName);Â
                System.out.println(                    "file unzip : "                    + newFile.getAbsoluteFile());Â
                // Create all non exists folders else we                // will get FileNotFoundException for                // compressed folder                new File(newFile.getParent()).mkdirs();Â
                FileOutputStream fos                    = new FileOutputStream(newFile);Â
                int len;                // read till there are characters                while ((len = zis.read(buffer)) > 0) {                    fos.write(buffer, 0, len);                }Â
                // Closing file output stream connections                fos.close();Â
                ze = zis.getNextEntry();            }Â
            // Closing all remaining connections            zis.closeEntry();            zis.close();Â
            // Display message for successful compilatuiona            // nd run            System.out.println(                "Successfully compiled and executed.");        }Â
        // Catch block to handle exceptions        catch (IOException ex) {Â
            // Display the exception along with line number            // using printStackTrace() method            ex.printStackTrace();        }    }} |
Output: On console generated after entering your path you will get the following outputÂ
Successfully compiled and executed.
It can be perceived from the image where the file as shown in below media as follows:Â
Â

