The Wayback Machine - https://web.archive.org/web/20240910142217/https://www.geeksforgeeks.org/how-to-zip-and-unzip-files-in-java/
Open In App

How to Zip and Unzip Files in Java?

Last Updated : 26 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java Programming we have a lot of features available for solving real-time problems. Here I will explain how to Zip files and How to Unzip files by using Java Programming. Mostly zip and unzip files are used for zip the files for save storage, easy to share, and other purposes. In this article, we will learn how to zip and unzip files using the Java Programming Language.

Prerequisites:

Zip and Unzip files in Java

For Zip files in Java programming, Java programming provides classes and methods for handling files. So Here we have the FileOutputStream class is used for Handling files and ZipOutputStream is used for Zip the Files by using putNextEntry() and ZipEntry(). These two methods are used to Move normal files into Zip files and the next method is used to convert into a single Zip file.

ZipInputStream and FileInputStream these two classes are used to Unzip the Zipped files. Once extract the files from the Zip file then those files are saved into the root folder individually. And we have methods getNextEntry() and mkdirs() for handling the compression of the files and creating folders. Below I provide the example for zip and unzip files in Java with related output.

Example:

Java
import java.io.*;
import java.util.zip.*;

public class ZipExample {

    // Method to zip files
    public static void zipFiles(String[] srcFiles, String zipFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            byte[] buffer = new byte[1024];
            
            for (String srcFile : srcFiles) {
                File fileToZip = new File(srcFile);
                try (FileInputStream fis = new FileInputStream(fileToZip)) {
                    zos.putNextEntry(new ZipEntry(fileToZip.getName()));
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                    zos.closeEntry();
                }
            }
        }
    }

    // Method to unzip files
    public static void unzip(String zipFile, String destFolder) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            while ((entry = zis.getNextEntry()) != null) {
                File newFile = new File(destFolder + File.separator + entry.getName());
                if (entry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    new File(newFile.getParent()).mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        int length;
                        while ((length = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, length);
                        }
                    }
                }
            }
        }
    }

      // Main Function
    public static void main(String[] args) {
        try {
            // Zip files
            String[] filesToZip = {"file1.txt", "file2.txt"};
            String zipFileName = "compressed.zip";
            zipFiles(filesToZip, zipFileName);
            System.out.println("Files zipped successfully.");

            // Unzip files
            String destinationFolder = "unzipped";
            unzip(zipFileName, destinationFolder);
            System.out.println("Files unzipped successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Output of Zip UnZip Program

Output


Final Result Unzipped File:

Output Folders

Output Folders

Explanation of the above Program:

  • First we create a Java class, after that we take two files in Java project folder.
  • After this we created two methods in Java Class. The zipFiles() is used for zip the files, This method takes two inputs to handle files
  • And the unzip() This method also take two inputs those are zip file and destination folder.
  • In main(), we call these two methods from main method and from this main method we provide required inputs for those two methods.
  • Finally we print the result on the Java console.


Similar Reads

Java Program to Read and Print All Files From a Zip File
A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip file and after reading it, the contents inside it wou
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Create Password Protected Zip File in Java
Primarily, java does not have any function or package that will create a password-protected zip file without using some native codes. Java has some useful library which is good but they use some native codes to perform their task that makes their usage platform dependent to some extent. Whereas in the zip4j library we are just using java code witho
5 min read
ZIP API in Java
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 tha
5 min read
How to find and open the Hidden files in a Directory using Java
Pre-requisites: Java File Handling So far the operations using Java programs are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. In this article, we will see how to ope
3 min read
Compressing and Decompressing files in Java
DeflaterOutputStream and InflaterInputStream  classes are provided in Java to compress and decompress the file contents. These classes provide useful methods that can be used for compressing  the file content. Compressing a File using DeflaterOutputStream This class implements an output stream filter for compressing data in the "deflate" compressio
4 min read
Working with JAR and Manifest files In Java
Prerequisite - JAR file format Whenever a developer wants to distribute a version of his software, then all he want is to distribute a single file and not a directory structure filled with class files. JAR files were designed for this purpose. A JAR file can contain both class files and other file types like sound and image files which may be inclu
6 min read
Compressing and Decompressing files using GZIP Format in java
The java.util.zip package provides classes compress and decompress the file contents. FileInputStream, FileOutputStream and GZIPOutputStream classes are provided in Java to compress and decompress the files. Compressing a File using GZIPOutputStream Methods used in the program read(): Reads a byte of data. Present in FileInputStream. int read() wri
2 min read
Java Program to List all Files in a Directory and Nested Sub-Directories
Prerequisites: File class Given a main directory/folder, list all the files from it, and if this directory has other nested sub-directories, list files from them. It is pretty easy to observe a simple recursion pattern in the above problem. Algorithm : Create a File object for the main directory.Get an array of files for the main directory.If array
4 min read
How to Read and Write XML Files in Java?
XML is defined as the Extensible Markup Language, and it is mostly used as a format for storing and exchanging data between systems. To read and write XML files, Java programming offers several easily implementable libraries. The most widely used library is the built-in JAXP (Java API for XML processing). What is DOM?The Document Object Model (DOM)
5 min read
How to Read and Write JSON Files in Java?
JSON (JavaScript Object Notation) is simple but powe­rful. It helps the server and the client to share information. Applications like­ Java use special tools, or libraries, that re­ad JSON. In Java, some libraries make it easy to read and write JSON files. One popular library is Jackson. In this article, we will learn how to read and write JSON fil
4 min read
How to Read and Write Binary Files in Java?
The Binary files contain data in a format that is not human-readable. To make them suitable for storing complex data structures efficiently, in Java, we can read from the write to binary files using the Input and Output Streams. In this article, we will learn and see the code implementation to read and write binary files in Java. Syntax to Read fro
2 min read
How to Read and Write Files Using the New I/O (NIO.2) API in Java?
In this article, we will learn how to read and write files using the new I/O (NIO) API in Java. For this first, we need to import the file from the NIO package in Java. This NIO.2 is introduced from the Java 7 version. This provides a more efficient way of handling input and output operations compared to the traditional Java package java.io. Now, b
3 min read
JAR files in Java
A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform. In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image fi
3 min read
Java program to merge contents of all the files in a directory
Prerequisite : PrintWriter, BufferedReader. We are given a directory/folder in which n number of files are stored(We dont know the number of files) and we want to merge the contents of all the files into a single file lets say output.txt For the below example lets say the folder is stored at the path: F:\GeeksForGeeksFollowing are the steps: Create
2 min read
Files deleteIfExists() method in Java with Examples
The deleteIfExists() method of java.nio.file.Files help us to delete a file if the file exists at the path. we pass the path of the file as a parameter to this method. This method will return true if the file was deleted by this method; false if the file could not be deleted because it did not exist. If the file is a symbolic link then the symbolic
3 min read
Files delete() method in Java with Examples
The delete() method of java.nio.file.Files help us to delete a file located at the path passed as a parameter. This method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted. If the file is a directory then this method will delete
3 min read
Files getFileStore() method in Java with Examples
getFileStore() method of java.nio.file.Files help us to return the FileStore object which represents the file store where a file is located. Once you get a reference to the FileStore you can apply filestore type of operation to get information of filestore. Syntax: public static FileStore getFileStore(Path path) throws IOException Parameters: This
2 min read
Files isHidden() method in Java with Examples
isHidden() method of java.nio.file.Files help us to check whether or not a file is hidden. This method return true if the file is considered hidden else it returns false. The exact definition of hidden is platform or provider dependent. On UNIX, for example, a file is considered to be hidden if its name begins with a period character ('.'). On Wind
2 min read
Files isReadable() method in Java with Examples
isReadable() method of java.nio.file.Files help us to check whether Java virtual machine has appropriate privileges that would allow it to open this file for reading or not. This method test file is readable or not. This method checks that a file exists or not and if file exists then it is readable or not. This method returns true if the file exist
2 min read
Files isWritable() method in Java with Examples
isWritable() method of java.nio.file.Files help us to check whether Java virtual machine has appropriate privileges that would allow it to open this file for writing or not. It means this method test file is writable or not. This method checks that a file exists or not and if file exists then it is writable or not. This method returns true if the f
2 min read
Files isExecutable() method in Java with Examples
isExecutable() method of java.nio.file.Files help us to check whether a file is executable. This method checks that a file exists on this path or not and if it exists then Java virtual machine has appropriate privileges to execute the file or not. The semantics may differ when checking access to a directory. For example, on UNIX systems, checking f
2 min read
Files size() method in Java with Examples
size() method of java.nio.file.Files help us to get the size of a file (in bytes). This method returns the file size, in bytes by taking the path of the file as a parameter. The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons. The size of files that are not regular files is impl
2 min read
Comparing Path of Two Files in Java
The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the program is requesting the file modification access which is already in use by another program. To compare the path of the file, compareTo() method of File Class is used. compareTo()
2 min read
Practice Tags :