Angle Bracket <> in Java with Examples Different types of Recursions in Java Java Lambda Filter Example Java Program for Shopping Bill Pythagorean Triplet with Given Sum Using Single Loop in Java TemporalAdjusters lastInMonth() method in Java with Examples ZIP API in Java Atomic reference in Java Digit Extraction in Java DRY (Don't Repeat Yourself) Principles in Java with Examples Empty array in Java Is main method compulsory in Java? Java I/O Operation - Wrapper Class vs Primitive Class Variables Java Program to Find the Perimeter of a Rectangle Java Thread Priority Java Type Erasure Need of Concurrent Collections in Java Nested ArrayList in Java Print Odd and Even Numbers by Two Threads in Java Square pattern in Java TemporalAdjusters next() method in Java with Examples What does start() function do in multithreading in Java Convert Number to Words Problem in Java Detect And Remove Cycle in a Single Linked List in Java Evolution of Interfaces in Java How to pad a String in Java Implementing Patricia Trie in Java Java Program to Find the Most Repeated Word in a Text File java.util.UUID class in Java ReadWriteLock Interface in Java Reference Data Types in Java Sort An Array According to The Count of Set Bits in Java Alternate Vowel and Consonant string in Java Built-in Exceptions in Java with Examples Capture the Pawns Problem in Java Collections.shuffle() Method in Java with Examples JDBC MySQL Localhost 3306 Alternate Vowel and Consonant string in Java Built-in Exceptions in Java with Examples Capture the Pawns Problem in Java Collections.shuffle() Method in Java with Examples Convert Number to Words Problem in Java Detect And Remove Cycle in a Single Linked List in Java Evolution of Interfaces in Java How to pad a String in Java Implementing Patricia Trie in Java Java Program to Find the Most Repeated Word in a Text File java.util.UUID class in Java ReadWriteLock Interface in Java Reference Data Types in Java Sort An Array According to The Count of Set Bits in Java JDBC MySQL Localhost 3306 Adding a Character as Thousands Separator to Given Number in Java Circular Primes in Java Equilibrium Index Problem in Java Java String regionMatches() Method with Examples LFU Cache Problem in Java Longest Repeating and Non-Overlapping Substring in Java Prefix Suffix Search in Java Product Array Puzzle Problem in Java Russian Doll Envelopes Problem in Java Second Most Repeated Word in a Sequence in Java Special Two-Digit Numbers in a Binary Search Tree in Java Swap Corner Words and Reverse Middle Characters in Java Toggle K bits Problem in Java Upside Down Binary Tree in Java Verbal Arithmetic Puzzle Problem in Java Insert a String into another String in Java Print Shortest Path to Print a String on Screen in Java Search Insert Position in Java BST Sequences in Java Burrows - Wheeler Data Transform Algorithm in Java Convert BST to Min Heap in Java Fibonacci Sum in Java Get name of current method being executed in Java Keith number in Java Longest Even Length Substring in Java Saint-Exupery Numbers in Java Standard practice for protecting sensitive data in Java application Strobogrammatic number in Java Types of Methods in Java Programming Valid Number Problem in Java Boggle Search Problem in Java Convert Java Object to JSON String using Jackson API Generate Random String in Java Java Program to Determine the Unicode Code Point at Given Index in Strin Java 18 snippet tags Jumping Numbers in Java Junction Numbers in Java Find Four Elements that Sums to a given value in Java How to print string vertically in Java How to remove in string in Java Three-Way Partition Problem in Java Apocalyptic Number in Java Check if the given two matrices are mirror images of one another in Java Duplicate Characters Problem in Java Duplicate Parenthesis Problem in Java Sum of Minimum and Maximum Elements of all Subarrays of Size K in Java Triple Shift Operator in Java Valid Pairing of Numbers in Java Valid Sudoku problem in Java Java Cipher Class Kth Missing Positive Number in Java Largest Square Matrix Problem in Java Length of the longest substring without repeating characters in Java Minimum Cost to Make String Valid Problem in Java Ordered pair in Java Range Addition Problem in Java

ZIP API in Java

The Java API for ZIP files is a set of classes and interfaces that allow you to create, read, and write ZIP files. The API is part of the Java standard library, so you need not download additional JAR files.

Features of ZIP API

  • To use the ZIP API, you must first create a ZipFile object. This object represents the ZIP file you want to create, read, or write. Once you have started a ZipFile object, you can add files to the ZIP file, remove files from the ZIP file, and get a list of the files in the ZIP file.
  • To add a file to a ZIP file, you use the addFile() method. This method takes the file name you want to add as its argument. The file will be added to the ZIP file with its current name.
  • To remove a file from a ZIP file, you use the removeFile() method. This method takes the file name you want to remove as its argument. The file will be removed from the ZIP file if it exists.
  • To get a list of the files in a ZIP file, you use the getEntries() method. This method returns an Enumeration of ZipEntry objects. Each ZipEntry object represents a file in the ZIP file.
  • The ZIP API also provides several other methods that you can use to manipulate ZIP files. For example, you can use the getComment() method to get the comment for a ZIP file and the setComment() method to set the comment for a ZIP file.

The ZIP API is a powerful tool that can be used to create, read, and write ZIP files. The API is easy to use, and it is well-documented.

As usual, we will start by discussing constructors before moving on to methods and finally putting the ZIP API into effect. Beginning with the constructors, let us do the following:

Constructors

  • Default constructor: The default constructor creates a zip entry with the given name and accepts a string argument called name.
ZipEntry() {}
  • Parameterized constructor: A new zip entry gets created by using the specified file

File file: For opening and reading ZIP files for a specified file object

ZipFile(File) {}

For opening and reading ZIP files for a specified file object

ZipFile(File file, Charset charset) {{}     

Methods

Now let us 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

Let us understand Java Program to Illustrate ZIP API in order to zip a file.

Filename: ZIPAPI.java

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class ZIPAPI {

    public static void main(String[] args) {

        // Source file to be zipped

        String sourceFilePath = "example.txt";

        // Destination ZIP file

        String zipFilePath = "example.zip";

        try {

            // Creating a ZipOutputStream to write to the zip file

            FileOutputStream fos = new FileOutputStream(zipFilePath);

            ZipOutputStream zipOut = new ZipOutputStream(fos);

            // Creating a ZipEntry for the source file

            ZipEntry zipEntry = new ZipEntry(new File(sourceFilePath).getName());

            zipOut.putNextEntry(zipEntry);

            // Reading the contents of the source file and writing to the zip file

            FileInputStream fis = new FileInputStream(sourceFilePath);

            byte[] buffer = new byte[1024];

            int bytesRead;

            while ((bytesRead = fis.read(buffer)) > 0) {

                zipOut.write(buffer, 0, bytesRead);

            }

            // Closing resources

            fis.close();

            zipOut.close();

            fos.close();

            System.out.println("File successfully zipped!");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Output:

File successfully zipped!

The following Java program illustrates how to unzip a file using ZIP API.

Filename: UnzipAPI.java

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

public class UnzipAPI {

    public static void main(String[] args) {

        // Path to the ZIP file

        String zipFilePath = "example.zip";

        // Directory to extract the contents to

        String extractToDirectory = "extracted_files";

        try {

            // Creating a ZipInputStream to read from the zip file

            ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));

            // Creating the output directory if it doesn't exist

            File directory = new File(extractToDirectory);

            if (!directory.exists()) {

                directory.mkdir();

            }

            // Iterating through each entry in the zip file

            ZipEntry entry = zipIn.getNextEntry();

            while (entry != null) {

                // Creating a new file in the output directory

                String filePath = extractToDirectory + File.separator + entry.getName();

                File outFile = new File(filePath);

                // Creating directories if they don't exist

                if (entry.isDirectory()) {

                    outFile.mkdirs();

                } else {

                    // Writing the contents of the entry to the file

                    FileOutputStream fos = new FileOutputStream(outFile);

                    byte[] buffer = new byte[1024];

                    int bytesRead;

                    while ((bytesRead = zipIn.read(buffer)) != -1) {

                        fos.write(buffer, 0, bytesRead);

                    }

                    fos.close();

                }

                // Moving to the next entry

                zipIn.closeEntry();

                entry = zipIn.getNextEntry();

            }

            // Closing resources

            zipIn.close();

            System.out.println("File successfully unzipped to: " + extractToDirectory);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

Output:

File successfully unzipped to: extracted_files