• How to Zip Files in Java

    Below is an example on how to zip files in Java. You can also select multiple files and add to zip file. In this method, pass the name of the zip that you want to be created. The zip file will be save in the temporary folder of your computer. This method will return the zip file which you can save anywhere or do something else. This throws IOException if the file you want to add in zip throws an error.

        /**
         * Zip the files and add those in the temp location with the zip file name provided.
         *
         * @param zipFileName file name of the zip file to be set. File name should be complete with .zip extension
         * @param addToZip    files to be compress and added to the zip
         * @return zip file the zip file that was created
         * @throws IOException
         */
        public static File zipFiles(String zipFileName, List<File> addToZip) 
                 throws IOException {
    
            String zipPath = System.getProperty("java.io.tmpdir") 
                 + File.separator + zipFileName;
            new File(zipPath).delete(); //delete if zip file already exist
    
            try (FileOutputStream fos = new FileOutputStream(zipPath);
                 ZipOutputStream zos = new ZipOutputStream(
                      new BufferedOutputStream(fos))) {
                zos.setLevel(9); //level of compression
    
                for (File file : addToZip) {
                    if (file.exists()) {
                        try (FileInputStream fis = new FileInputStream(file)) {
                            ZipEntry entry = new ZipEntry(file.getName());
                            zos.putNextEntry(entry);
                            for (int c = fis.read(); c != -1; c = fis.read()) {
                                zos.write(c);
                            }
                            zos.flush();
                        }
                    }
                }
            }
            File zip = new File(zipPath);
            if (!zip.exists()) {
                throw new FileNotFoundException("The created zip file could not be found");
            }
            return zip;
        }
    

    Related Post