
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to compress a file in Java?
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.......
- Related Questions & Answers
- How to un-compress a file in Java?
- How to compress and un-compress the data of a file in Java?
- How to truncate a file in Java?
- Compress String in C++
- Best Way to compress mysqldump?
- How to convert a Kotlin source file to a Java source file?
- How to Compress files with ZIPFILE module in Python.
- How to create a pdf file in Java?
- How to delete a temporary file in Java?
- How to compress Python objects before saving to cache?
- How to append data to a file in Java?
- How to search a file in a directory in java
- How we can compress large Python files?
- How to open a plain text file in Java?
- How to convert File into a Stream in Java?
Advertisements