Wednesday, August 18, 2010

Creating a ZIP file in JAVA

Using ZipOutputStream and  Class in java.util.zip package we can craete an zip entry for the list of files.
The following gives the sample to create an zip file "outfile.zip" .This zip whill be created using the contents those given in the 'filenames' array.

1:  // These are the files to include in the ZIP file  
2:  String[] filenames = new String[]{"filename1", "filename2"};  
3:  // Create a buffer for reading the files  
4:  byte[] buf = new byte[1024];  
5:  try {  
6:    // Create the ZIP file  
7:    String outFilename = "outfile.zip";  
8:    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));  
9:    // Compress the files  
10:    for (int i=0; i<filenames.length; i++) {  
11:      FileInputStream in = new FileInputStream(filenames[i]);  
12:      // Add ZIP entry to output stream.  
13:      out.putNextEntry(new ZipEntry(filenames[i]));  
14:      // Transfer bytes from the file to the ZIP file  
15:      int len;  
16:      while ((len = in.read(buf)) > 0) {  
17:        out.write(buf, 0, len);  
18:      }  
19:      // Complete the entry  
20:      out.closeEntry();  
21:      in.close();  
22:    }  
23:    // Complete the ZIP file  
24:    out.close();  
25:  } catch (IOException e) {  
26:  }  

Source : http://www.exampledepot.com

No comments:

Post a Comment