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:
FileOutputStream
object for the given zip name.ZipOutputStream
object using the FileOutputStream
object.putNextEntry
and write
methods to add that file to the ZipOutputStream
object. See main.java. filethree
one.txt
, two.txt
, and three.txt
, in the current directory, which you can see on the sidebar of the above code snippet.outputZipFileName
, with a value, educative.zip
, which represents the final zip file to be created. filesToBeWritten
, that contains the path of the files to be zipped.printZipFiles
method to print the zip files present in the current directory.c
method. There is no zip file present, so nothing will be printed. 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.for
loop for the filesToBeWritten
array. File
object from the file name.FileInputStream
object, fis
, which can be used to read the file as a stream.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. write
method.closeEntry
method.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.