Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

Compress and Uncompress File


The DeflaterOutputStream and InflaterInputStream classes provide mechanism to compress and uncompress the data in the deflate 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. class Compress{
  4. public static void main(String args[]){
  5. try{
  6. FileInputStream fin=new FileInputStream(“Deflater.java”);
  7. FileOutputStream fout=new FileOutputStream(“def.txt”);
  8. DeflaterOutputStream out=new DeflaterOutputStream(fout);
  9. int i;
  10. while((i=fin.read())!=-1){
  11. out.write((byte)i);
  12. out.flush();
  13. }
  14. fin.close();
  15. out.close();
  16. }catch(Exception e){System.out.println(e);}
  17. System.out.println(“rest of the code”);
  18. }
  19. }

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. class UnCompress{
  4. public static void main(String args[]){
  5. try{
  6. FileInputStream fin=new FileInputStream(“def.txt”);
  7. InflaterInputStream in=new InflaterInputStream(fin);
  8. FileOutputStream fout=new FileOutputStream(“D.java”);
  9. int i;
  10. while((i=in.read())!=-1){
  11. fout.write((byte)i);
  12. fout.flush();
  13. }
  14. fin.close();
  15. fout.close();
  16. in.close();
  17. }catch(Exception e){System.out.println(e);}
  18. System.out.println(“rest of the code”);
  19. }
  20. }

Comments

comments