Monday, 23 December 2013

File Compress and decompress in java


File Compress and decompress java program-

For example first we have to create folder and copy file into the folder which one we want to compress.

Open net beans create new project and write below code for compress your file.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.DeflaterOutputStream;
public class CompressFile {
public static void main(String[] args) {
try{
FileInputStream fin=new FileInputStream("D:\\Compress\\introduction.pdf");
FileOutputStream fout=new FileOutputStream("D:\\Compress\\res.txt");
DeflaterOutputStream out=new DeflaterOutputStream(fout);
int i;
while((i=fin.read())!=-1){
out.write((byte)i);
out.flush();
}
fin.close();
out.close();
}
catch(Exception e){System.out.println(e);}
System.out.println("your file compressed");
}

 
Output-

After running this program we get compressed file in same folder as below


 
res is compressed file of this pdf file if we check the size of this file it will be less then pdf actual size.


After that write code for decompress the same file as shown below,


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.InflaterInputStream;
public class Decompress {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\Compress\\res.txt");
InflaterInputStream in=new InflaterInputStream(fin);
FileOutputStream fout=new FileOutputStream("D:\\Compress\\D.pdf");
int i;
while((i=in.read())!=-1){
fout.write((byte)i);
fout.flush();
}
fin.close();
fout.close();
in.close();
}catch(Exception e){System.out.println(e);}
System.out.println("your file decompressed");
}
}

Output -

And we get decompressed file in same folder as ,


Decompressed file is same as our original file.











No comments:

Post a Comment