16

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.

Community
  • 1
  • 1
Luistar15
  • 1,699
  • 3
  • 14
  • 16

3 Answers3

50

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.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I was trying using ByteArrayOutputStream, but your example works perfectly. Thank you – Luistar15 May 13 '11 at 16:26
  • @user752679: I originally wrote out a sample using ByteArrayOutputStream, but as your question says you want to write it to a file... – Jon Skeet May 13 '11 at 16:29
  • note: dont forget to close the `streamWriter` or else you will get `unexpected EOF` while trying to open up `*.gzip` - https://stackoverflow.com/a/12100352/432903 – prayagupa Mar 30 '19 at 17:10
3

Same solution as Jon, just used try with resources

try (FileOutputStream output = new FileOutputStream("filename.gz");
     Writer writer = new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8")) {
    
    writer.write("someText");
}
Walter Tross
  • 12,237
  • 2
  • 40
  • 64
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
3

Have a look at GZIPOutputStream - you should be able to use this in exactly the same way as any other outputstream to write to a file - it'll just automatically write it in the gzip compressed format.

DaveH
  • 7,187
  • 5
  • 32
  • 53