Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: save string as gzip file

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.

like image 485
Luistar15 Avatar asked May 13 '11 16:05

Luistar15


People also ask

How do I compress a gzip file in Java?

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 .

What is GZIP in Java?

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.

How do you GZIP an object in Java?

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 ...


1 Answers

There are two orthogonal concepts here:

  • Converting text to binary, typically through an OutputStreamWriter
  • Compressing the binary data, e.g. using GZIPOutputStream

So in the end you'll want to:

  • Create an OutputStream which writes to wherever you want the result (e.g. a file or in memory via a ByteArrayOutputStream
  • Wrap that OutputStream in a GZIPOutputStream
  • Wrap the GZIPOutputStream in an OutputStreamWriter using an appropriate charset (e.g. UTF-8)
  • Write the text to the OutputStreamWriter
  • Close the writer, which will flush and close everything else.

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.

like image 63
Jon Skeet Avatar answered Oct 07 '22 10:10

Jon Skeet