This example shows how to create a ZIP file in Java.
Program code compress given files and folders and creates a ZIP file archive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { public void createZipFile() { try { String inputFileName = "test.txt"; String zipFileName = "compressed.zip"; //Create input and output streams FileInputStream inStream = new FileInputStream(inputFileName); ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName)); // Add a zip entry to the output stream outStream.putNextEntry(new ZipEntry(inputFileName)); byte[] buffer = new byte[1024]; int bytesRead; //Each chunk of data read from the input stream //is written to the output stream while ((bytesRead = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, bytesRead); } //Close zip entry and file streams outStream.closeEntry(); outStream.close(); inStream.close(); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { new Main().createZipFile(); } } |