AdSense

AdSense3

Friday 14 November 2014

Compressing and Uncompressing File

The DeflaterOutputStream and InflaterInputStream classes provide mechanism to compress and uncompress the data in thedeflate compression format.


DeflaterOutputStream class:

The DeflaterOutputStream class is used to compress the data in the deflate compression format. It provides facility to the other compression filters, such as GZIPOutputStream.

Example of Compressing file using DeflaterOutputStream class

In this example, we are reading data of a file and compressing it into another file using DeflaterOutputStream class. You can compress any file, here we are compressing the Deflater.java file
  1. import java.io.*;  
  2. import java.util.zip.*;  
  3.   
  4. class Compress{  
  5. public static void main(String args[]){  
  6.   
  7. try{  
  8. FileInputStream fin=new FileInputStream("Deflater.java");  
  9.   
  10. FileOutputStream fout=new FileOutputStream("def.txt");  
  11. DeflaterOutputStream out=new DeflaterOutputStream(fout);  
  12.   
  13. int i;  
  14. while((i=fin.read())!=-1){  
  15. out.write((byte)i);  
  16. out.flush();  
  17. }  
  18.   
  19. fin.close();  
  20. out.close();  
  21.   
  22. }catch(Exception e){System.out.println(e);}  
  23. System.out.println("rest of the code");  
  24. }  
  25. }  

InflaterInputStream class:

The InflaterInputStream class is used to uncompress the file in the deflate compression format. It provides facility to the other uncompression filters, such as GZIPInputStream class.

Example of uncompressing file using InflaterInputStream class

In this example, we are decompressing the compressed file def.txt into D.java .
  1. import java.io.*;  
  2. import java.util.zip.*;  
  3.   
  4. class UnCompress{  
  5. public static void main(String args[]){  
  6.   
  7. try{  
  8. FileInputStream fin=new FileInputStream("def.txt");  
  9. InflaterInputStream in=new InflaterInputStream(fin);  
  10.   
  11. FileOutputStream fout=new FileOutputStream("D.java");  
  12.   
  13. int i;  
  14. while((i=in.read())!=-1){  
  15. fout.write((byte)i);  
  16. fout.flush();  
  17. }  
  18.   
  19. fin.close();  
  20. fout.close();  
  21. in.close();  
  22.   
  23. }catch(Exception e){System.out.println(e);}  
  24. System.out.println("rest of the code");  
  25. }  

No comments:

Post a Comment