How to compress a file in Java?

JavaObject Oriented ProgrammingProgramming

The DeflaterOutputStream class of Java is used to compress the given data and stream it out to the destination.

The write() method of this class accepts the data (in integer and byte format), compresses it and, writes it to the destination of the current DeflaterOutputStream object. To compress a file using this method &Minus;

  • Create a FileInputStream object, by passing the path of the file to be compressed in String format, as a parameter to its constructor.
  • Create a FileOutputStream object, by passing the path of the output file, in String format, as a parameter to its constructor.
  • Create a DeflaterOutputStream object, by passing the above created FileOutputStream object, as a parameter to its constructor.
  • Then, read the contents of the input file and write using the write() method of the DeflaterOutputStream class.

Example

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
public class CompressingFiles {
   public static void main(String args[]) throws IOException {
      //Instantiating the FileInputStream
      String inputPath = "D:\\ExampleDirectory\\logo.jpg";
      FileInputStream inputStream = new FileInputStream(inputPath);
      //Instantiating the FileOutputStream
      String outputPath = "D:\\ExampleDirectory\\compressedLogo.txt";
      FileOutputStream outputStream = new FileOutputStream(outputPath);
      //Instantiating the DeflaterOutputStream
      DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream);
      int contents;
      while ((contents=inputStream.read())!=-1){
         compresser.write(contents);
      }
      compresser.close();
      System.out.println("File compressed.......");
   }
}

Output

File compressed.......
raja
Published on 15-Oct-2019 10:05:25
Advertisements