A ZIP file is a collection of one or more files and/or folders that have been compressed into a single file for easy transfer and compression.
We can follow the steps below to create a ZIP file from an existing file.
Here, we assume the name of the file to be compressed is file.txt
, and the compressed file name is file.zip
.
FileOutputStream
object for the ZIP file to be created.ZipOutputStream
class. Pass the FileOutputStream
object created in Step 2 as the parameter to the constructor.FileInputStream
object for the text file to be compressed.ZipEntry
object that takes the input text file name as a constructor parameter.Each file in the ZIP file is represented by a
ZipEntry
(java.util.zip.ZipEntry). Hence, to read/write from a ZIP file,ZipEntry
is used.
ZipEntry
object created in Step 5 into the ZipOutputStream
object, via the putNextEntry
method.ZipOutputStream
object via the write
method.ZipEntry
object.Note: Use
try-with-resources
to autoclose the stream objects.
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class Zip {public static void main(String[] args) throws IOException {String fileName = "file.txt";String zipFileName = "file.zip";if (!Files.isRegularFile(Path.of(fileName))) {System.err.println("Please provide an existing file.");return;}ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));FileInputStream fileInputStream = new FileInputStream(fileName);ZipEntry zipEntry = new ZipEntry(fileName);zipOutputStream.putNextEntry(zipEntry);byte[] buffer = new byte[1024];int length;while ((length = fileInputStream.read(buffer)) > 0) {zipOutputStream.write(buffer, 0, length);}zipOutputStream.closeEntry();zipOutputStream.close();fileInputStream.close();}}