Zip File Folder Example Using Java 8 (2021) | TechGeekNext >>

Zip File Folder Example Using Java 8 (2021)

In this tutorial, will show you how to zip the folder (compress recursively all files and child folders) using Java 8 and using Core Java libraries. The core libraries belongs to package. Lets start with zipping the folder. I have created some text files in Notes folder as shown below:
Folder to zip
Will give source folder path as 'D:\Notes' and program will zip/compress all files into zip called We wrapped Files.walk in try with resources block so that stream can be closed.

Example to Zip Folder

package com.techgeeknext;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class ZipUtility {

    private List <String> fileList;
    private static final String NOTES_ZIP = "D:\\";
    private static final String FOLDER_TO_ZIP = "D:\\Notes";

    public static void main(String[] args) throws IOException {

    public static void zip(final String sourcNoteseDirPath, final String zipFilePath) throws IOException {
        Path zipFile = Files.createFile(Paths.get(zipFilePath));

        Path sourceDirPath = Paths.get(sourcNoteseDirPath);
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
             Stream<Path> paths = Files.walk(sourceDirPath)) {
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
                        try {
                            Files.copy(path, zipOutputStream);
                        } catch (IOException e) {

        System.out.println("Zip is created at : "+zipFile);


Zip is created at : D:\

Java Unzip File Folder Example :

In next tutorial, will learn how to Unzip the folder using Core Java libraries. To unzip a zip file, we will make use of ZipInputStream to read the zip file.
Checkout next post, we will see how to unzip files or directory using core Java features.

Recommendation for Top Popular Post :