Create ZIP File Example
This program demonstrates creating a ZIP file.
Problem Statement
Write a Java program that compresses multiple files into a ZIP archive.
Source Code
| 1 | import java.io.*; |
| 2 | import java.util.zip.*; |
| 3 | public class ZipCreateExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq ZIP Create Example"); |
| 6 | try(FileOutputStream fos=new FileOutputStream("archive.zip"); |
| 7 | ZipOutputStream zos=new ZipOutputStream(fos)) { |
| 8 | addFile(zos,"file1.txt"); |
| 9 | addFile(zos,"file2.txt"); |
| 10 | System.out.println("Eduinq ZIP Created Successfully"); |
| 11 | } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); } |
| 12 | } |
| 13 | static void addFile(ZipOutputStream zos,String filename) throws IOException { |
| 14 | FileInputStream fis=new FileInputStream(filename); |
| 15 | zos.putNextEntry(new ZipEntry(filename)); |
| 16 | byte[] buffer=new byte[1024]; int len; |
| 17 | while((len=fis.read(buffer))!=-1){ zos.write(buffer,0,len); } |
| 18 | zos.closeEntry(); fis.close(); |
| 19 | } |
| 20 | } |
Program Output
Eduinq ZIP Create Example Eduinq ZIP Created Successfully
Explanation
Uses ZipOutputStream to compress files. - Adds multiple entries into archive. - Exception handling ensures safe operations. - In enterprise systems, ZIP creation reduces storage and transfer size. Conclusion: Shows creating ZIP files.