java:将字符串另存为 gzip 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5994674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:52:41  来源:igfitidea点击:

java: save string as gzip file

javastringgzipcompression

提问by Luistar15

I'm java beginner, I need something like this:

我初学java,我需要像这样

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.

我不知道该怎么做。

回答by Jon Skeet

There are two orthogonal concepts here:

这里有两个正交概念:

  • Converting text to binary, typically through an OutputStreamWriter
  • Compressing the binary data, e.g. using GZIPOutputStream
  • 将文本转换为二进制,通常通过 OutputStreamWriter
  • 压缩二进制数据,例如使用 GZIPOutputStream

So in the end you'll want to:

所以最后你会想要:

  • Create an OutputStreamwhich writes to wherever you want the result (e.g. a file or in memory via a ByteArrayOutputStream
  • Wrap that OutputStreamin a GZIPOutputStream
  • Wrap the GZIPOutputStreamin an OutputStreamWriterusing an appropriate charset (e.g. UTF-8)
  • Write the text to the OutputStreamWriter
  • Close the writer, which will flush and close everything else.
  • 创建一个OutputStream写到任何你想要结果的地方(例如一个文件或通过一个内存中的ByteArrayOutputStream
  • 把它包OutputStream在一个GZIPOutputStream
  • 包裹GZIPOutputStreamOutputStreamWriter使用适当的字符集(例如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 outputeven if we fail to create the writer, but we still need to close writerif everything is successful, in order to flush everything and finish writing the data.

请注意,output即使我们无法创建writer编写器,我也会关闭,但如果一切成功,我们仍然需要关闭,以便刷新所有内容并完成写入数据。

回答by DaveH

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.

看看GZIPOutputStream- 您应该能够以与任何其他输出流完全相同的方式使用它来写入文件 - 它只会自动以 gzip 压缩格式写入它。

回答by Niraj Sonawane

Same solution as Jon, just used try with resources

与 Jon 相同的解决方案,只是使用 try 与资源

  try (   FileOutputStream output = new FileOutputStream("filename.gz");
                Writer writer = new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8")) {

            writer.write("someText");


        }