4

私はInputStreamgzipされたデータを含む大きなデータを持っています。

InputStream のデータを直接変更することはできません。後でこれを使用するコードは、InputStream変更されていない圧縮データを想定しています。InputStream必要に応じて新しいものと交換できInputStreamますが、データは圧縮したままにする必要があります。

InputStreamデバッグ目的で、圧縮されていないコンテンツを出力する必要があります。

InputStreammy の圧縮されていないデータを aPrintStreamに出力する最も簡単な方法は何InputStreamですか?

4

1 に答える 1

1

これが私がやった方法です。

// 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 に書き込むまで残ります。

于 2013-02-01T01:31:49.923 に答える