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;
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......."); } }
File compressed.......