How to compress files in ZIP format in Java
Sometimes in your Java application you may need to compress files in zip format while file related applications. Luckily Java comes with inbuilt zip utility packages that can be use to compress any file in zip format. Here is a very straightforward tutorial to compress any file in zip format in Java program.
The concept of compressing the file in Java is quite straightforward and simple.
- Read the file with FileInputStream
- Use the Java zip utility and add to ZipEntry
- Output it to ZipOutputStream
- Once done close all resources.
File Compression Example in Java
We are going to compress the file ‘mylog.txt’ to ‘mycomressslog.zip’. The below Java program will do the compression of the file.
public class ZipAFileInJava
public static void main( String args )
File inputFile = new File("/home/hduser/test/mylog.txt");
String zipFile = "/home/hduser/test/mycomressslog.zip";
private static void zipTheFile(File sourceFile, String targetFile)
byte buffer = new byte;
FileInputStream in = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
ZipOutputStream zos = new ZipOutputStream(fos);
//Initialize the ZipEntry with the included file name, you can give any name in the parameter
ZipEntry ze= new ZipEntry(sourceFile.getName());
while ((len = in.read(buffer)) > 0)
zos.write(buffer, 0, len);
//Remember to close all opened resources.
System.out.println(sourceFile.getCanonicalPath()+" is zipped to "+targetFile);
Compression started... Done!!!!!! /home/hduser/test/mylog.txt is zipped to /home/hduser/test/mycomressslog.zip
The above program is capable of zipping a single file, we can even zip a complete folder recursively in a similar way but little bit different. In my next tutorial I will show how to recursively compress a folder into zip format using Java program.