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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public byte[] zipFiles(List<File> 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.
Thanks for post and exactly what is required.
Keep posting.