Saturday, July 3, 2010

Java Zip Examples


1. How to create ZIP file in java

package basics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipExample {

void zipFiles(String[] sourcsFiles, String destPath) {
// Create a buffer for reading the files
byte[] tempBufffer = new byte[1024];

ZipOutputStream out = null;
FileInputStream in = null;
try {
// Create the zip file instance.
out = new ZipOutputStream(new FileOutputStream(new File(
destPath)));

// Compress the files
for (int i = 0; i < sourcsFiles.length; i++) {
in = new FileInputStream(sourcsFiles[i]);

// This is to get file name
String zipEntyname = sourcsFiles[i].substring(sourcsFiles[i]
.lastIndexOf("/") + 1, sourcsFiles[i].length());
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(zipEntyname));

// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(tempBufffer)) > 0) {
out.write(tempBufffer, 0, len);
}

// Complete the entry
out.closeEntry();
in.close();
}

// Complete the ZIP file
out.close();
} catch (Exception e) {
} finally {
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
String[] sourcsFiles = { "C:/temp/one.properties",
"C:/temp/two.properties" };
new ZipExample().zipFiles(sourcsFiles, "C:/temp/files.zip");
}
}

There will be a zip file created at
C:/temp/files.zip

No comments:

Post a Comment