我从 HTTP 请求的响应开始:
InputStream responseInputStream = response.getEntityInputStream()
我需要对该响应进行 gzip 压缩,以便将其上传到 s3 并压缩保存:
this.s3.putObject(new PutObjectRequest(bucketName, key, gzippedResponseInputStream, meta));
我知道我可以从 responseInputStream
中获取 byte[]
数组,然后将它们 gzip 到一个新的 InputStream
中。但是,对于大量数据,这可能非常低效。
我知道在 SO 上也有人问过类似的问题,但我还没有发现任何似乎可以解决以 InputStream
开始并以 gzipped InputStream< 结束的特定需求
.
感谢您的帮助!
最佳答案
我认为您正在寻找 PipedInputStream
这是如何完成的。
public InputStrema getGZipStream() {
final PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try (final InputStream responseInputStream = response.getEntityInputStream();
){
pis.connect(pos);
Thread thread = new Thread() {
public void run () {
startWriting(pos, responseInputStream);
}
};
thread.start();
} catch(Exception e) {
e.printStackTrace();
}
return pis;
}
public void startWriting(OutputStream out, InputStream in) {
try (GZIPOutputStream gOut = GZIPOutputStream(out);) {
byte[] buffer = new byte[10240];
int len = -1;
while ((len = in.read(buffer)) != -1) {
gOut.write(buffer, 0, len);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
out.close();
} catch( Exception e) {
e.printStackTrace();
}
}
}
我还没有测试过这段代码,如果有效请告诉我。
关于java - 我如何 gzip 一个 InputStream 并返回一个 InputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924585/