简体   繁体   English

Java:写入OutputStream,然后将其用作InputStream

[英]Java: Write to OutputStream and then use it as InputStream

I want to get a file from a remote storage as an InputStream without saving it to the local File System. 我想从远程存储中获取一个文件作为InputStream而不将其保存到本地文件系统。 The remote storage provides a Java API with a method that takes an OutputStream and dumps the file data into it. 远程存储为Java API提供了一种方法,该方法接受OutputStream并将文件数据转储到其中。

void dump(OutputStream dest);

The easy way I've come up with is to create a temporary file, dump the data into it and reopen it as an InputStream. 我想出的简单方法是创建一个临时文件,将数据转储到其中并重新打开它作为InputStream。 But this approach creates a temporary file. 但是这种方法会创建一个临时文件。 Is there an easy way to achieve the same result without a proxy file? 有没有代理文件可以轻松实现相同的结果?

Two options: 两种选择:

Memory 记忆

If the "file" in question is small enough for it to be viable, you could read the data into a ByteArrayOutputStream , and then use its toByteArray method to construct a ByteArrayInputStream to read from. 如果所讨论的“文件”足够小以使其可行,则可以将数据读入ByteArrayOutputStream ,然后使用其toByteArray方法构造要读取的ByteArrayInputStream

Piping 管道

To avoid storing more in memory than necessary, you could use PipedOutputStream and PipedInputStream . 为避免在内存中存储超过必要的内容,可以使用PipedOutputStreamPipedInputStream

PipedOutputStream : PipedOutputStream

A piped output stream can be connected to a piped input stream to create a communications pipe. 管道输出流可以连接到管道输入流以创建通信管道。 The piped output stream is the sending end of the pipe. 管道输出流是管道的发送端。 Typically, data is written to a PipedOutputStream object by one thread and data is read from the connected PipedInputStream by some other thread. 通常,数据由一个线程写入PipedOutputStream对象,而某些其他线程从连接的PipedInputStream读取数据。

PipedInputStream : PipedInputStream

A piped input stream should be connected to a piped output stream; 管道输入流应连接到管道输出流; the piped input stream then provides whatever data bytes are written to the piped output stream. 然后,管道输入流提供写入管道输出流的任何数据字节。 Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. 通常,一个线程从PipedInputStream对象读取数据,并且某些其他线程将数据写入相应的PipedOutputStream。

You give the API the output stream, and read from the input stream. 您为API提供输出流,并从输入流中读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM