Zip Files using java.util.zip Package

java provides the ‘java.util.zip‘ package to compress and decompress the data

In the below example we are using ZipOutputStream Class for output stream filter for writing files in the ZIP file format, ZipEntry Class to represent the Zip file entry and ZipInputStream Class for input stream filter for reading files in the ZIP file format

package com.javaartifacts;

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

public class Zip {

public static void main(String[] args){

try{

byte[] buffer = new byte[1024];

File file = new File("d:\\file.txt");

FileOutputStream fos = new FileOutputStream("d:\\file.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
FileInputStream fis = new FileInputStream(file);

int len;
while((len = fis.read(buffer)) >0){
zos.write(buffer, 0, len);
}

fis.close();
zos.closeEntry();
zos.close();

System.out.println("file zipped succesfully");
}

catch(Exception ex){
ex.printStackTrace();
}
}

}

 
Reference

  1. http://www.oracle.com/technetwork/articles/java/compress-1565076.html

Leave a Reply

Your email address will not be published. Required fields are marked *