这就是我的做法。
// http://stackoverflow.com/a/12107486/82156
public static InputStream wrapInputStreamAndCopyToOutputStream(InputStream in, final boolean gzipped, final OutputStream out) throws IOException {
// Create a tee-splitter for the other reader.
final PipedInputStream inCopy = new PipedInputStream();
final TeeInputStream inWrapper = new TeeInputStream(in, new PipedOutputStream(inCopy));
new Thread(Thread.currentThread().getName() + "-log-writer") {
@Override
public void run() {
try {
IOUtils.copy(gzipped ? new GZIPInputStream(inCopy) : inCopy, new BufferedOutputStream(out));
} catch (IOException e) {
Log.e(TAG, e);
}
}
}.start();
return inWrapper;
}
此方法包装原始 InputStream 并返回包装器,从现在开始您需要使用它(不要使用原始 InputStream)。然后,它使用Apache Commons TeeInputStream使用线程将数据复制到 PipedOutputStream,并在此过程中可选地对其进行解压缩。
要使用,只需执行以下操作:
InputStream inputStream = ...; // your original inputstream
inputStream = wrapInputStreamAndCopyToOutputStream(inputStream,true,System.out); // wrap your inputStream and copy the data to System.out
doSomethingWithInputStream(inputStream); // Consume the wrapped InputStream like you were already going to do
后台线程将一直存在,直到前台线程消耗整个输入流,以块的形式缓冲输出并定期将其写入 System.out 直到全部完成。