繁体   English   中英

字符串到 GZIPOutputStream

[英]String to GZIPOutputStream

我试过搜索,但找不到任何东西。 我想要做的是遍历一个列表,在该列表中我从多个列表中的项目组合构造一个字符串。 然后我想将这些字符串转储到一个 gzip 文件中。 我只是将它转储到一个普通的 ascii 文本文件中,但我似乎无法让它与 gzipoutputstream 一起工作。 所以基本上,

循环创建字符串转储字符串到 gzipped 文件 endloop

如果可能,我想避免转储到纯文本文件然后对其进行 gzip 压缩,因为这些文件每个将近 100 兆。

是的,你可以做到这一点没有问题。 您只需要使用编写器将基于字符的字符串转换为基于字节的 gzip 流。

    BufferedWriter writer = null;
    try {
        GZIPOutputStream zip = new GZIPOutputStream(
            new FileOutputStream(new File("tmp.zip")));

        writer = new BufferedWriter(
            new OutputStreamWriter(zip, "UTF-8"));

        String[] data = new String[] { "this", "is", "some", 
            "data", "in", "a", "list" };

        for (String line : data) {
            writer.append(line);
            writer.newLine();
        }
    } finally {         
        if (writer != null)
            writer.close();
    }

另外,记住 gzip 只是压缩一个流,如果你想要嵌入文件,请参阅这篇文章: gzip archive with multiple files inside

try {
        String srcString = "the string you want to zip.";

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(stream);
        gzip.write(srcString.getBytes(StandardCharsets.UTF_8));
        gzip.close();

        // the gzip bytes you get
        byte[] zipBytes = stream.toByteArray();

    } catch (IOException ex) {
        // ...
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM