I'm java beginner, I need something like this:
String2GzipFile (String file_content, String file_name)
String2GzipFile("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "lorem.txt.gz")
I cant figure out how to do that.
Create a FileOutputStream to the destination file, that is the file path to the output compressed file. Create a GZIPOutputStream to the above FileOutputStream . Create a FileInputStream to the file you want to compress. Read the bytes from the source file and compress them using GZIPOutputStream .
Here in this tutorial, we will show you how you can easily compress files in GZIP in Java. As per the definition of GZIP in Wikipedia, GZIP is normally used to compress a single file. But we can compress multiple files by adding them in a tarball (. tar) before we compress them into a GZIP file.
Java object compression is done using the GZIPOutputStream class (this class implements a stream filter for writing compressed data in the GZIP file format) and passes it to the ObjectOutputStream class (this class extends OutputStream and implements ObjectOutput, ObjectStreamConstants) to write the object into an ...
There are two orthogonal concepts here:
OutputStreamWriter
GZIPOutputStream
So in the end you'll want to:
OutputStream
which writes to wherever you want the result (e.g. a file or in memory via a ByteArrayOutputStream
OutputStream
in a GZIPOutputStream
GZIPOutputStream
in an OutputStreamWriter
using an appropriate charset (e.g. UTF-8)OutputStreamWriter
For example:
FileOutputStream output = new FileOutputStream(fileName);
try {
Writer writer = new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8");
try {
writer.write(text);
} finally {
writer.close();
}
} finally {
output.close();
}
Note that I'm closing output
even if we fail to create the writer, but we still need to close writer
if everything is successful, in order to flush everything and finish writing the data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With