tangguo

如何将OutputStream转换为InputStream?

java

我正处于开发阶段,在那里我有两个模块,从一个模块我得到的输出为a OutputStream,第二个模块仅接受InputStream。您是否知道如何转换OutputStream为InputStream可以连接这两部分的方式(反之亦然,我是说真的)

谢谢


阅读 937

收藏
2020-11-20

共2个答案

小编典典

nOutputStream是您向其中写入数据的地方。如果某个模块公开了OutputStream,则期望在另一端读取一些内容。

InputStream另一方面,暴露出的信息表示您需要侦听此流,并且会有一些数据可以读取。

因此可以将一个连接InputStream到一个OutputStream

InputStream----read---> intermediateBytes[n] ----write----> OutputStream

正如有人提到的那样,这就是IOUtils的copy()方法可以让您完成的工作。走另一条路是没有道理的…希望这是有道理的

更新:

当然,我对这一点的思考越多,我越能看到这实际上是一项要求。我知道一些提及Piped输入/输出流的评论,但是还有另一种可能性。

如果公开的输出流是ByteArrayOutputStream,那么您始终可以通过调用toByteArray()方法来获取全部内容。然后,您可以使用ByteArrayInputStream子类创建输入流包装器。这两个都是伪流,它们基本上都只是包装一个字节数组。因此,以这种方式使用流在技术上是可行的,但对我来说仍然很奇怪…

2020-11-20
小编典典

似乎有很多链接和其他类似内容,但没有使用管道的实际代码。使用java.io.PipedInputStream和的优点java.io.PipedOutputStream是没有额外的内存消耗。ByteArrayOutputStream.toByteArray()返回原始缓冲区的副本,这意味着内存中的任何内容现在都有两个副本。然后写一个数据InputStream意味着您现在有了数据的三个副本。

编码:

// take the copy of the stream and re-write it to an InputStream
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread(new Runnable() {
    public void run () {
        try {
            // write the original OutputStream to the PipedOutputStream
            // note that in order for the below method to work, you need
            // to ensure that the data has finished writing to the
            // ByteArrayOutputStream
            originalByteArrayOutputStream.writeTo(out);
        }
        catch (IOException e) {
            // logging and exception handling should go here
        }
        finally {
            // close the PipedOutputStream here because we're done writing data
            // once this thread has completed its run
            if (out != null) {
                // close the PipedOutputStream cleanly
                out.close();
            }
        }   
    }
}).start();

这段代码假定originalByteArrayOutputStreama是一个,ByteArrayOutputStream因为它通常是唯一可用的输出流,除非您要写入文件。我希望这有帮助!这样做的好处在于,由于它在一个单独的线程中,因此也可以并行工作,因此,无论消耗您的输入流,还是从旧的输出流中流出。这是有益的,因为缓冲区可以保持较小,并且您将拥有更少的延迟和更少的内存使用量。

2020-11-20