Compressing and Decompressing files using GZIP Format in java
The java.util.zip package provides classes compress and decompress the file contents. FileInputStream, FileOutputStream and GZIPOutputStream classes are provided in Java to compress and decompress the files.
Compressing a File using GZIPOutputStream
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Methods used in the program
- read(): Reads a byte of data. Present in FileInputStream.
- write(): Writes a byte of data, Present in FileOutputStream.
void write(int b)
In this example, we have a text file in /home/saket/Desktop/GeeksforGeeks/compress.java drive under “GeeksforGeeks” Folder and we are compressing and generating the GZip file in the same folder.
File Successfully compressed
After Running the above program, It will compress the compress.java file:
Decompressing a File using GZIPOutputStream
File Successfully decompressed
Current State after compiling:
Note : Here decom.java contains the above code.
After Running the above program, It will decompress the compress.gz and a file named decompress.java will be created.
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.