How to create a zip from multiple files in Java

Overview

We can use the ZipOutputStream object for writing files in the zip file format. To create a zip file from multiple files, we perform the following:

  1. Get the path of the files to be zipped.
  2. Get the name for the zip file to be created.
  3. Create a FileOutputStream object for the given zip name.
  4. Create a new ZipOutputStream object using the FileOutputStream object.
  5. Read the provided file and use the putNextEntry and write methods to add that file to the ZipOutputStream object.
  6. Close all the opened streams.

Example

main.java
three.txt
two.txt
one.txt
See main.java. file
three

Explanation

  • We create three files, one.txt , two.txt, and three.txt, in the current directory, which you can see on the sidebar of the above code snippet.
  • Line 10: We create a string variable, outputZipFileName, with a value, educative.zip, which represents the final zip file to be created.
  • Line 11: We create a string array, filesToBeWritten, that contains the path of the files to be zipped.
  • Lines 52–61: We create a printZipFiles method to print the zip files present in the current directory.
  • Line 13: We print the zip files present in the current directory by calling the c method. There is no zip file present, so nothing will be printed.
  • Lines 15–16: We create a FileOutputStream object fos with the name educative.zip. This will create a file output stream to write to the file. With the fos object, we create a ZipOutputStream object, zos, which will have methods to write files to the zip.
  • Line 18: We create a for loop for the filesToBeWritten array.
  • Line 20: We create a File object from the file name.
  • Line 21: From the file object, we create a FileInputStream object, fis, which can be used to read the file as a stream.
  • Line 24: We use the putNextEntry method of ZipOutputStream to begin writing a new zip file entry. This method will position the stream to the start of the entry data.
  • Lines 26–33: We read the content of the file and write into the zip file using the write method.
  • Line 35: Once the current file is written to the zip, we close the current zip entry by calling the closeEntry method.
  • Line 38: We close the input stream of the source file.

Once all the files are written to the zip, we call the printZipFiles method. Now we have a zip file with the name educative.zip. This file name will be printed on the console.

Free Resources