Sunday, July 5, 2009

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.

2 comments:

  1. To my mind exist some types of tools for solving problems and one of them is the next. It solved out all my problems with zip files and probably will help with like issues - how to fix a zip file cracked.

    ReplyDelete
  2. Thanks a ton it was a very good support, now to make zip file using java, creating a zip file in java is definitely very easy with your recommendation. Thank you

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)