Java Programing laungage

java.util Projects

java.util Project 1

ZIP file Creation

It is a popular method of data compression. It can hold many files in compressed format. we can say the files are stored in the zip format with compression and the file which is in the zip format holds the ".zip" extension.

Previous Home Next

we can also make executable file in zip format an can archive data from the zip file by extracting it. For create a zip file from other type of file, following program gives you the best way of making it possible through you code in java application.

Code Description

Many methods and APIs are used in the following example for making a zip file from the given file. These explanation is as as follows.

ZipOutputStream

It is the class of java.util.zip.*; package. This class is used to compression the file whether the file is uncompressed.

ZipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION)

This method is used to mentioned the setLevel() method of ZipOutputStream class which sets the level of the compression process. This method take an argument which is the built-in field of the Deflater class.

Deflater

This is the class of java.util.zip.*; package. This class provides the compression using the ZLIBcompression library.

Example


package r4r;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class zipcreatetest {
	



public static void main(String[] args) throws IOException{
 System.out.print("Enter the file name to zip : ");
 BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
 String filezip = br.readLine();
 File file = new File(filezip);
 if(!file.exists()){
 System.out.println("File is not found.");
 System.exit(0);
 }
 System.out.print("Enter the zip file name : ");
 String zipFileName = br.readLine();
 if (!zipFileName.endsWith(".zip"))
 zipFileName = zipFileName + ".zip";
 byte[] buffer = new byte[18024];
 try{
 ZipOutputStream zos = new ZipOutputStream
		(new FileOutputStream(zipFileName));
 zos.setLevel(Deflater.DEFAULT_COMPRESSION);
 FileInputStream in = new FileInputStream(filezip);
 zos.putNextEntry(new ZipEntry(filezip));
 int len;
 while ((len = in.read(buffer)) > 0){
 zos.write(buffer, 0, len);
 }
 zos.closeEntry();
 in.close();
 zos.close();
 }
 catch (IllegalArgumentException iae){
 iae.printStackTrace();
 System.exit(0);
 }
 catch (FileNotFoundException fnfe){
 fnfe.printStackTrace();
 System.exit(0);
 }
 catch (IOException ioe){
 ioe.printStackTrace();
 System.exit(0);
 }
 }
}

Previous Home Next