Searching...
Friday, 4 October 2013

How to create zip file in Java ?

11:29

java.util.zip.ZipOutputStream class is used to create zip file in java. Here is one example to create zip file in java.

package com.pretechsol;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CreateZipFileExample {
	public static void main(String[] args) {
		try {
			File newfile = new File("pretech.txt");
			FileWriter fw = new FileWriter(newfile);
			fw.write("Hai this is zip testing");
			fw.close();
			File zipfile = new File("pretech.zip");
			FileInputStream fis;
			fis = new FileInputStream(newfile);
			FileOutputStream fos = new FileOutputStream(zipfile);
			ZipOutputStream zos = new ZipOutputStream(fos);
			ZipEntry ze = new ZipEntry("pretech.txt");
			zos.putNextEntry(ze);
			byte[] buf = new byte[1024];
			int len;
			while ((len = fis.read(buf)) > 0) {
				zos.write(buf, 0, len);
			}
			System.out.println("Please check this zip file pretech.zip");
			fis.close();
			zos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

0 comments: