Java:写入OutputStream,然后作为InputStream使用
Java: Write to OutputStream and then use it as InputStream
我想从远程存储中获取文件作为 InputStream,而不将其保存到本地文件系统。远程存储提供了一个 Java API 方法,该方法采用 OutputStream 并将文件数据转储到其中。
void dump(OutputStream dest);
我想出的简单方法是创建一个临时文件,将数据转储到其中,然后将其作为 InputStream 重新打开。但是这种方法会创建一个临时文件。有没有一种简单的方法可以在没有代理文件的情况下获得相同的结果?
两个选项:
内存
如果所讨论的 "file" 足够小以使其可行,您可以将数据读入 ByteArrayOutputStream
, and then use its toByteArray
method to construct a ByteArrayInputStream
以供读取。
管道
为避免在内存中存储不必要的内容,您可以使用 PipedOutputStream
and PipedInputStream
。
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.
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.
你给 API 输出流,然后从输入流中读取。
我想从远程存储中获取文件作为 InputStream,而不将其保存到本地文件系统。远程存储提供了一个 Java API 方法,该方法采用 OutputStream 并将文件数据转储到其中。
void dump(OutputStream dest);
我想出的简单方法是创建一个临时文件,将数据转储到其中,然后将其作为 InputStream 重新打开。但是这种方法会创建一个临时文件。有没有一种简单的方法可以在没有代理文件的情况下获得相同的结果?
两个选项:
内存
如果所讨论的 "file" 足够小以使其可行,您可以将数据读入 ByteArrayOutputStream
, and then use its toByteArray
method to construct a ByteArrayInputStream
以供读取。
管道
为避免在内存中存储不必要的内容,您可以使用 PipedOutputStream
and PipedInputStream
。
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 connectedPipedInputStream
by some other thread.
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.
你给 API 输出流,然后从输入流中读取。