I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream
to an OutputStream
in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).
So, given an InputStream
in
and an OutputStream
out
, is there a simpler way to write the following?
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
Using Guava's
ByteStreams.copy()
:Using Java7 and try-with-resources, comes with a simplified and readable version.
A IMHO more minimal snippet (that also more narrowly scopes the length variable):
As a side note, I don't understand why more people don't use a
for
loop, instead opting for awhile
with an assign-and-test expression that is regarded by some as "poor" style.If you are using Java 7, Files (in the standard library) is the best approach:
Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use
file.toPath()
to get path from file.To write into an existing file (e.g. one created with
File.createTempFile()
), you'll need to pass theREPLACE_EXISTING
copy option (otherwiseFileAlreadyExistsException
is thrown):Try Cactoos:
More details here: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html
Java 9
Since Java 9,
InputStream
provides a method calledtransferTo
with the following signature:As the documentation states,
transferTo
will:So in order to write contents of a Java
InputStream
to anOutputStream
, you can write: