Tuesday, October 9, 2012

How to make Zip file using Java, Creating a ZIP file in Java

To run this tutorial
1. Create one folder src
2. Put test1.txt and test2.txt in src folder.
3. After run this code, you will get myZip.zip file in src folder.

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

public class MakeZip {
public static void main(String[] args) {
String[] filesToZip = {"src\\test1.txt","src\\test2.txt"};
//String[] filesToZip = {"src\\test1.txt"};
String ZipedFileName = "src\\myZip.zip";
zipConversion(filesToZip, ZipedFileName);
}

public static void zipConversion(String[] files, String ZipedFileName){
byte[] buffer = new byte[1024];
try{
FileOutputStream outputFile = new FileOutputStream(ZipedFileName);
ZipOutputStream zipFile = new ZipOutputStream(outputFile);
for(int i=0;i<files.length;i++){
FileInputStream inFile = new FileInputStream(files[i]);
zipFile.putNextEntry(new ZipEntry(files[i]));
int length;
while ((length = inFile.read(buffer)) > 0) {
zipFile.write(buffer, 0, length); }

zipFile.closeEntry();
inFile.close();
}

zipFile.close();
System.out.println("Files Ziped Successfully");
}catch(IOException e){ e.printStackTrace(); }
}
}

You can either give one file to zip or any number of files in fileToZip string array.

0 comments:

Post a Comment