Support Online
Skip to main content

Java ZIP File and Folder Compression Guide (java.util.zip)

🧠 What Will You Learn in This Guide?

In this guide, you will learn how to compress files and folders using Java's java.util.zip package.
Using the ZipOutputStream and ZipEntry classes you will convert a single file or an entire directory into a ZIP archive.


🧩 1. ZIP Processing Logic

Java's java.util.zip package contains basic tools for compression:

  • ZipOutputStream: Writes data to the ZIP file.
  • ZipEntry: Represents each file or folder in the ZIP archive.

What to do to add a file to ZIP:

  1. Create an FileOutputStream for the target ZIP file.
  2. Start burning via ZipOutputStream.
  3. Create a new ZipEntry for each file.
  4. Read the file and write it to the ZIP stream.
  5. Close streams.

📁 2. Compressing a Single File into ZIP

The following example compresses the file /home/genixnode/logs/rapor.txt to rapor_arsiv.zip.

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

public class ZipSingleFile {
public static void main(String[] args) {
File file = new File("/home/genixnode/logs/rapor.txt");
String zipFileName = "/home/genixnode/logs/rapor_arsiv.zip";
zipSingleFile(file, zipFileName);
}

private static void zipSingleFile(File file, String zipFileName) {
try (FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream fis = new FileInputStream(file)) {

ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);

byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}

System.out.println(file.getName() + " sıkıştırıldı: " + zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}

➡️ This example converts a single file to ZIP format.


📂 3. Compressing a Folder into a ZIP Archive

To compress a folder, it is necessary to process all files in subdirectories recursively.


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

public class ZipDirectory {
private final List<String> fileList = new ArrayList<>();

public static void main(String[] args) {
File sourceDir = new File("/home/genixnode/web_projeleri/yedek");
String zipName = "/home/genixnode/web_projeleri/yedek.zip";
new ZipDirectory().zipDirectory(sourceDir, zipName);
}

public void zipDirectory(File dir, String zipFileName) {
try {
populateFileList(dir);
try (FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos)) {

for (String filePath : fileList) {
String relativePath = filePath.substring(dir.getAbsolutePath().length() + 1);
zos.putNextEntry(new ZipEntry(relativePath));

try (FileInputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
System.out.println("Sıkıştırılıyor: " + filePath);
}
System.out.println("Klasör başarıyla sıkıştırıldı: " + zipFileName);
}
} catch (IOException e) {
e.printStackTrace();
}
}

private void populateFileList(File dir) {
File[] files = dir.listFiles();
if (files == null) return;
for (File file : files) {
if (file.isFile()) fileList.add(file.getAbsolutePath());
else populateFileList(file);
}
}
}

➡️ This code compresses all files in the specified directory and preserves the directory structure.


🧮 4. Performance and Memory Tips

💡 Status🧾 Description
Buffer SizeSmall blocks like byte[1024] use memory efficiently.
Relative PathsIt is important to preserve the folder structure when ZIP is opened.
Empty FoldersIt is not included by default; If desired, ZipEntry must be added manually.
Character SetPrevent corruption in Turkish filenames using UTF-8.

❓ Frequently Asked Questions (FAQ)

  1. Why do I have to use ZipEntry?

Each file or folder is represented as a ZipEntry in the ZIP archive. This object holds name and compression information.

  1. Why use relative file path?

If the absolute path is used, the full path will be recreated when the ZIP is opened. The relative path ensures that the directory structure is preserved.

  1. How to optimize memory usage?

By reading files piece by piece (buffer), compression can be done without filling up the entire memory.

  1. What formats are supported other than ZIP?

The java.util.zip package also provides the GZIP and Deflater/Inflater classes.

  1. Why do IOException errors occur?

It usually occurs due to lack of access permission, incorrect file path, or the file being locked by another process.


🎯 Result

In this guide, you learned how to compress files and folders in ZIP format in Java. You can perform archiving operations safely, efficiently and easily by using ZipOutputStream and ZipEntry classes.

💬 By distributing your Java application on GenixNode, you can immediately try your file operations in a high-performance cloud environment!