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:

You can also set the compression method and compression level using the following ZipOutputStream’s  methods:

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.