Pages

Compress single file in zip format in java

Java has a rich library. We can perform compression operation in java by using "java.util.zip" library. For compressing a file in zip format we use ZipOutputStream class. It allows us to write file iin a zip file. It accepts an OutputStream object ZipOutputStream(OutputStream out); putNextEntry() method allows us to append a file at the end of the zip file. To compress a single file into zip follow the following steps:
  1. Read file with "FileInputStream"
  2. Add the file name to be compressed to "ZipEntry" and output it to "ZipOutputStream".

The following program compress a single file.
It reads a file "compressMe.txt" and comress it into a zip file "comDemo.zip".


CompressFile.java
import java.io.*;
import java.util.zip.*;

class CompressFile{
public static void main(String[] args){
byte[] buffer = new byte[1024]; //size of the buffer

try{
FileOutputStream fileOutStream = new FileOutputStream("comDemo.zip"); 
ZipOutputStream zipOutStream = new ZipOutputStream(fileOutSteam);
//file to be compressed;
ZipEntry zipEntry = new ZipEntry("compressMe.txt");
//place to the destination
zipOut.putNextEntry(zipEntry);

FileInputStream in = new FileInputStream("compressMe.txt");
int len;
while((len = in.read(buffer)) > 0){
zipOut.write(buffer, 0, len);
}
in.close();
zipOut.close();
System.out.println("done");
}
catch(IOException ioEx){
System.out.println(ioEx.getMessage());
System.out.println("Compression Failed!"):

}
}
}

@msucil

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment