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
java: save string as gzip file
提问by Luistar15
回答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
OutputStream
which writes to wherever you want the result (e.g. a file or in memory via aByteArrayOutputStream
- Wrap that
OutputStream
in aGZIPOutputStream
- Wrap the
GZIPOutputStream
in anOutputStreamWriter
using 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
- 包裹
GZIPOutputStream
在OutputStreamWriter
使用适当的字符集(例如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.
请注意,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");
}