We help IT Professionals succeed at work.

Zipping files using Java.util.zip

snajalm
snajalm used Ask the Experts™
on
How would it be possible to zip files inside a folder into a single archive using java.util.zip api?  For instance I have a few XMLs generated inside a folder.  I'd need to compress these generated XMLs for each account into a single zip file and FTP them through to a remote server.

Regards,
Sam
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Here are intetesting resources, explanation

int BUFFER = 2048;
FileOutputStream fos = new 
  FileOutputStream(entry.getName());
BufferedOutputStream dest = new 
  BufferedOutputStream(fos, BUFFER);


The first step is to create a ZipOutputStream object, to which we pass the output stream of the file we wish to write to. Here is how you create a ZIP file entitled "myfigs.zip":
FileOutputStream dest = new 
  FileOutputStream("myfigs.zip");
ZipOutputStream out = new 
  ZipOutputStream(new BufferedOutputStream(dest));
Once the target zip output stream is created, the next step is to open the source data file. In this example, source data files are those files in the current directory. The list command is used to get a list of files in the current directory:
File f = new File(".");
String files[] = f.list();
for (int i=0; i<files.length; i++) {
   System.out.println("Adding: "+files[i]);
   FileInputStream fi = new FileInputStream(files[i]);
   // create zip entry
   // add entries to ZIP file
}


Note: This code sample is capable of compressing all files in the current directory. It doesn't handle subdirectories. As an exercise, you may want to modify Code Sample 3 to handle subdirectories.



Create a zip entry for each file that is read:
ZipEntry entry = new ZipEntry(files[i]))
Before you can write data to the ZIP output stream, you must first put the zip entry object using the putNextEntry method:
out.putNextEntry(entry);
Write the data to the ZIP file:
int count;
while((count = origin.read(data, 0, BUFFER)) != -1) {
   out.write(data, 0, count);
}
Finally, you close the input and output streams:
origin.close();
out.close();

http://java.sun.com/developer/technicalArticles/Programming/compression/

http://www.crazysquirrel.com/computing/java/basics/java-directory-zipping.jspx
http://www.roseindia.net/java/example/java/io/ZipFileExample.shtml
http://stackoverflow.com/questions/740375/directories-in-a-zip-file-when-using-java-util-zip-zipoutputstream

Open in new window

Author

Commented:
Thanks for the spot on answer.