Tuesday, February 17, 2009

ZIP Files in Java

The ZIP file format has become extremely popular for the distribution and storage of files. ZIP files allow for compression, making transporting a set of files from one location to another faster.Depending on the source file types being compressed, ZIP files can provide significant space savings. ZIP archives can also maintain the directory structure of files that are compressed, making the ZIP format a formidable file transport mechanism.

The java.util.zip package allows for the programmatic reading and writing of the ZIP and GZIP formats.Learning how to use the offerings of the java.util.zip package might best be facilitated via example.

The below example FileZip class has only one method makeZip(), takes two parameters,
String Array- Pass the files paths as strings which you want to Zip.
String - The target zip file name to save as.

Code:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFiles {
public String makeZip(String[] filesToZip,String zipFileName){
byte[] buffer = new byte[18024];
if(!zipFileName.endsWith(".zip")){
zipFileName+=".zip";
}
try {
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
// Set the compression ratio
out.setLevel(Deflater.DEFAULT_COMPRESSION);
// iterate through the array of files, adding each to the zip file
int filesSiz=filesToZip.length;
for (int i = 0; i < style="color: rgb(0, 153, 0);">// Associate a file input stream for the current file
File file2Zip=new File(filesToZip[i].toString());
InputStream in = new BufferedInputStream(new FileInputStream(file2Zip));
// Add ZIP entry to output stream.
String fileExctNm=filesToZip[i].substring(filesToZip[i].lastIndexOf("/")+1);
out.putNextEntry(new ZipEntry(fileExctNm));
// Transfer bytes from the current file to the ZIP file
int len;
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
// Close the current entry
out.closeEntry();
// Close the current file input stream
in.close();
}
// Close the ZipOutPutStream
out.close();
}
catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return new File(zipFileName).toString();
}
}

No comments: