Reading/writing compressed and not compressed files in Java
on java and tricks
Main reason for this post is trying don’t repeat yourself (DRY) because, often, I fall in the recursive need to read and write compressed and not compressed files (mainly JSON and CSV).
Let’s to see first how to read text files. Note I’m working with (relatively small) text files so:
The read methods returns an String with the whole content.
I’m using BufferedReader to read line by line.
Note: there are more than one way to do things. In the entry Best way to read a text file, where you can find many different ways to read a text file depending on your JDK version and the size of the file.
Similarly to write a String to a file:
To read/write compressed files, that is with binary data, we need to work with streams and buffers. So to read a GZIP compressed file and obtain a String:
and similarly to write a String to a GZip compressed file:
Next you can find a couple of great links with Java code for various JDK versions: