java.util.Iterator<String> 到 gzip 数据的 InputStream

java.util.Iterator<String> to InputStream of gzipped data

我的客户有一个 API,它将 InputStream 作为参数,而我的数据来自 java.util.Iterator,所以基本上我需要将数据从一个 Iterator 传输到 InputStream。更重要的是,我想以 GZIP 格式传输它,所以基本上我需要生成一个包含 Iterator 压缩内容的 InputStream。

因为我想尽可能快和内存高效,我希望有一个 "streaming" 解决方案(我已经知道我可以用 GZIPOutputStream 将数据写入文件,然后用文件输入流)

您需要使用 Deflater to compress the data, and you need to implement an InputStream, where you should implement at least the read(), read(byte[] b, int off, int len), and close() 方法编写自己的逻辑。

这是我在 pseudo-code 中关于如何实施 read 的看法:

public int read(byte[] b, int off, int len) {
    if deflater finished:
        return -1
    if deflater needs input:
        get next string from iterator
        deflater.setInput(s.getBytes("UTF-8"))
        if iterator at end:
            deflater.finish()
    deflate into b using off and len
}

那当然是简化了。您需要正确初始化 deflater、处理空迭代器、用换行符分隔字符串等。