How to create a zip file in Java

In this tutorial, we show how to create a zip file from multiple files in Java.

1- ByteArrayOutputStream & ZipOutputStream

Using ByteArrayOutputStream and ZipOutputStream classes provided by the JDK, you can generate a zip file out of multiple files.

The following utility method accepts a list of File objects and generates a zip file as a byte array:

public byte[] zipFiles(List files){

	byte[] result = null;
		
	try (ByteArrayOutputStream fos = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(fos);) {
	        for (File fileToZip : files) {
	        	try (FileInputStream fis = new FileInputStream(fileToZip);) {
	        		ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
		            zipOut.putNextEntry(zipEntry);
		            
		            IOUtils.copy(fis, zipOut);
	        	}
	        }
	        zipOut.close();
	        fos.close();
	        
	        result = fos.toByteArray();
	}
	catch (Exception ex) 
	{
		ex.printStackTrace();
	}
		
	return result;
}

That’s it.

3.3 3 votes
Article Rating

Hussein Terek

Owner of programmergate.com, I have a passion for software engineering and everything related to Java environment.

guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Atul
Atul
9 months ago

Thanks for post and exactly what is required.
Keep posting.