これが私がやった方法です。
// 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 に書き込むまで残ります。