What's the simplest way in modern Java (using only the standard libraries) to read all of standard input until EOF into a byte array, preferably without having to provide that array oneself? The stdin data is binary stuff and doesn't come from a file.
I.e. something like Ruby's
foo = $stdin.read
The only partial solution I could think of was along the lines of
byte[] buf = new byte[1000000];
int b;
int i = 0;
while (true) {
b = System.in.read();
if (b == -1)
break;
buf[i++] = (byte) b;
}
byte[] foo[i] = Arrays.copyOfRange(buf, 0, i);
... but that seems bizarrely verbose even for Java, and uses a fixed size buffer.
I'd use Guava and its
ByteStreams.toByteArray
method:Without using any 3rd party libraries, I'd use a
ByteArrayOutputStream
and a temporary buffer:... possibly encapsulating that in a method accepting an
InputStream
, which would then be basically equivalent toByteStreams.toByteArray
anyway...If you're reading from a file, Files.readAllBytes is the way to do it.
Otherwise, I'd use a ByteBuffer: