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:
- Get the path of the files to be zipped.
- Get the name for the zip file to be created.
- Create a
FileOutputStreamobject for the given zip name. - Create a new
ZipOutputStreamobject using theFileOutputStreamobject. - Read the provided file and use the
putNextEntryandwritemethods to add that file to theZipOutputStreamobject. - Close all the opened streams.
Example
main.java
three.txt
two.txt
one.txt
See main.java. filethree
Explanation
- We create three files,
one.txt,two.txt, andthree.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
printZipFilesmethod 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
cmethod. There is no zip file present, so nothing will be printed. - Lines 15–16: We create a
FileOutputStreamobjectfoswith the nameeducative.zip. This will create a file output stream to write to the file. With thefosobject, we create aZipOutputStreamobject,zos, which will have methods to write files to the zip. - Line 18: We create a
forloop for thefilesToBeWrittenarray. - Line 20: We create a
Fileobject from the file name. - Line 21: From the file object, we create a
FileInputStreamobject,fis, which can be used to read the file as a stream. - Line 24: We use the
putNextEntrymethod ofZipOutputStreamto 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
writemethod. - Line 35: Once the current file is written to the zip, we close the current zip entry by calling the
closeEntrymethod. - 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.