0

I have to a class that generates an Excel file, class takes an output stream, intended for a FileOutputWriter. However I need to upload the file to S3 later, so saving it to a file would be an unnecessary step. To upload a file to S3 do I need it as an input stream.

I have therefore been looking for a way to convert an output stream to an input stream or transfer the data to an input stream.

I have tried PipeOutputStream, but xlsFile.write(outstr); just blocks forever when using a PipedOutputStream, using a FileOutputStream will it work fine and write the file.

PipedInputStream inputStream = new PipedInputStream();
try (OutputStream outstr = new PipedOutputStream(inputStream)) {
    xlsFile.write(outstr);
    outstr.flush();
    return inputStream;
}
Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
Androme
  • 2,399
  • 4
  • 43
  • 82
  • 2
    Because you're doing it in a single thread. – Lyubomyr Shaydariv Dec 02 '16 at 22:47
  • I imagine you'd be able to use the solution provided here: http://stackoverflow.com/questions/43157/easy-way-to-write-contents-of-a-java-inputstream-to-an-outputstream – Display Name Dec 02 '16 at 22:50
  • 1
    `PipedInputStream`/`PipedOutputStream` are supposed to be processed in different threads. Processing them in a single threads causes the thread to block itself. See an example at http://stackoverflow.com/a/23874232/166589 – Lyubomyr Shaydariv Dec 02 '16 at 22:58
  • Since this only works when the entire contents has been buffered, just write to a `ByteArrayOutputStream` and return a `ByteArrayInputStream` wrapping the resulting array. – Holger Dec 07 '16 at 15:01

1 Answers1

0

JDK 9 has added InputStream#transferTo(OutputStream out) for this functionality, though JDK 9 is not yet released. Early releases are available here.

Warren Nocos
  • 1,222
  • 1
  • 14
  • 29