In this tutorial, you will learn how to compress files in ZIP format using the java.util.zip package. You know, Java has great support for writing and reading ZIP files via the easy-to-use API. With this feature, you can compress/decompress data on the fly in your Java programs.

 

1. Steps to Compress a File in Java

Here are the steps to compress a file using Java code:

  • Open a ZipOutputStream that wraps an OutputStream like FileOutputStream. The ZipOutputStream class implements an output stream filter for writing in the ZIP file format.
  • Put a ZipEntry object by calling the putNextEntry(ZipEntry) method on the ZipOutputStream. The ZipEntry class represents an entry of a compressed file in the ZIP file.
  • Read all bytes from the original file by using the Files.readAllBytes(Path) method.
  • Write all bytes read to the output stream using the write(byte[] bytes, int offset, int length) method.
  • Close the ZipEntry.
  • Close the ZipOutputStream.
You can also set the compression method and compression level using the following ZipOutputStream’s  methods:

  • setMethod(int method): there are 2 methods: DEFLATED (the default) which compresses the data; and STORED which doesn’t compress the data (archive only).
  • setLevel(int level): sets the compression level ranging from 0 to 9 (the default).
Now, let’s see some examples in action.

 

2. Compress a Single File Example

The following program compresses a file whose path is passed from the command line:

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

/**
 * This Java program demonstrates how to compress a file in ZIP format.
 *
 * @author www.codejava.net
 */
public class ZipFile {

	private static void zipFile(String filePath) {
		try {
			File file = new File(filePath);
			String zipFileName = file.getName().concat(".zip");

			FileOutputStream fos = new FileOutputStream(zipFileName);
			ZipOutputStream zos = new ZipOutputStream(fos);

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

			byte[] bytes = Files.readAllBytes(Paths.get(filePath));
			zos.write(bytes, 0, bytes.length);
			zos.closeEntry();
			zos.close();

		} catch (FileNotFoundException ex) {
			System.err.format("The file %s does not exist", filePath);
		} catch (IOException ex) {
			System.err.println("I/O error: " + ex);
		}
	}

	public static void main(String[] args) {
		String filePath = args[0];
		zipFile(filePath);
	}
}
Run this program like this:

java ZipFile <file_path>
For example, compress a file in the current directory:

java ZipFile JavaIO.doc


This results in the JavaIO.doc.zip file got created in the current directory.

 

3. Compress Multiple Files Example

The following program compresses multiple files into a single ZIP file. The file paths are passed from the command line, and the ZIP file name is name of the first file followed by the .zip extension. Here’s the code:

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

/**
 * This Java program demonstrates how to compress multiple files in ZIP format.
 *
 * @author www.codejava.net
 */
public class ZipFiles {

	private static void zipFiles(String... filePaths) {
		try {
			File firstFile = new File(filePaths[0]);
			String zipFileName = firstFile.getName().concat(".zip");

			FileOutputStream fos = new FileOutputStream(zipFileName);
			ZipOutputStream zos = new ZipOutputStream(fos);

			for (String aFile : filePaths) {
				zos.putNextEntry(new ZipEntry(new File(aFile).getName()));

				byte[] bytes = Files.readAllBytes(Paths.get(aFile));
				zos.write(bytes, 0, bytes.length);
				zos.closeEntry();
			}

			zos.close();

		} catch (FileNotFoundException ex) {
			System.err.println("A file does not exist: " + ex);
		} catch (IOException ex) {
			System.err.println("I/O error: " + ex);
		}
	}

	public static void main(String[] args) {
		zipFiles(args);
	}
}
Run this program like this:

java ZipFiles <file1> <file2> <file3> …
For example, compress 3 files in the current directory:

java ZipFiles doc1.txt doc2.txt doc3.txt
The result is a ZIP file named doc1.txt.zip created which contains the 3 files in compressed format.

 

4. Compress a Whole Directory Example

Using the walk file tree feature of Java NIO, you can write a program that compresses a whole directory (including sub files and sub directories) with ease. The following is source code of such a program:

import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
import java.nio.file.attribute.*;

/**
 * This Java program demonstrates how to compress a directory in ZIP format.
 *
 * @author www.codejava.net
 */
public class ZipDir extends SimpleFileVisitor<Path> {

	private static ZipOutputStream zos;

	private Path sourceDir;

	public ZipDir(Path sourceDir) {
		this.sourceDir = sourceDir;
	}

	@Override
	public FileVisitResult visitFile(Path file,
			BasicFileAttributes attributes) {

		try {
			Path targetFile = sourceDir.relativize(file);

			zos.putNextEntry(new ZipEntry(targetFile.toString()));

			byte[] bytes = Files.readAllBytes(file);
			zos.write(bytes, 0, bytes.length);
			zos.closeEntry();

		} catch (IOException ex) {
			System.err.println(ex);
		}

		return FileVisitResult.CONTINUE;
	}

	public static void main(String[] args) {
		String dirPath = args[0];
		Path sourceDir = Paths.get(dirPath);

		try {
			String zipFileName = dirPath.concat(".zip");
			zos = new ZipOutputStream(new FileOutputStream(zipFileName));

			Files.walkFileTree(sourceDir, new ZipDir(sourceDir));

			zos.close();
		} catch (IOException ex) {
			System.err.println("I/O Error: " + ex);
		}
	}
}
Note that the directory path is given from the command line. Run this program like this:

java ZipDir <dir_path>
For example, compress a sub directory in the current directory:

java ZipDir JavaTutorials
This compresses the whole directory JavaTutorials into the JavaTutorials.zip file.

 

API References:

 

Related Java Zip File Tutorials:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#6Khen Hermoso2021-07-19 21:45
Hi author, this code didn't work for me because String zipFileName = dirPath.concat(".zip"); will only produce a file name, no the full path to the file. This causes OutputStream to error out with file not found. The code that worked for me was String zipFileName = filePath.concat(".zip"); which reconstructs the input argument AND retains the full path to the file.
Quote
#5Dreeperte2020-08-23 12:33
Never mind it was just saving the file in the wrong directory.
Quote
#4Dreeperte2020-08-23 12:23
Quoting Manikanta:
I tried zipping 10 MB csv file using ( Compress a Single File Example). But its not generating any zip file and there is no exception too........



Same problem here, using the Single File example even with the absolute pass its not generating any zip file and there is no exception.
Quote
#3Manikanta2019-09-20 01:39
Quoting Manikanta:
I tried zipping 10 MB csv file using ( Compress a Single File Example). But its not generating any zip file and there is no exception too........




Hey Its working. In windows we have to give absolute path for zip file.
Quote
#2Manikanta2019-09-19 05:26
I tried zipping 10 MB csv file using ( Compress a Single File Example). But its not generating any zip file and there is no exception too........
Quote