3

I want to get a file from a remote storage as an InputStream without saving it to the local File System. The remote storage provides a Java API with a method that takes an OutputStream and dumps the file data into it.

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. But this approach creates a temporary file. Is there an easy way to achieve the same result without a proxy file?

1 Answer 1

6

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.

Piping

To avoid storing more in memory than necessary, you could use 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.

You give the API the output stream, and read from the input stream.

Not the answer you're looking for? Browse other questions tagged or ask your own question.