Here's one way to solve this without relying on third-party libraries:

inputStream.reset();
byte[] bytes = new byte[inputStream.available()];
DataInputStream dataInputStream = new DataInputStream(inputStream);
dataInputStream.readFully(bytes);

Or if you don't mind using thirdparties (Commons IO):


byte[] bytes = IOUtils.toByteArray(is);

Guava also helps:

byte[] bytes = ByteStreams.toByteArray(inputStream);
Answer from Mark Bramnik on Stack Overflow
🌐
GitHub
github.com › wvlet › airframe › issues › 1329
airframe-grpc: NoSuchMethodError java.io.InputStream.readAllBytes()[B · Issue #1329 · wvlet/airframe
October 22, 2020 - Reported in #1319 by @NomadBlacky · This error happens only in JDK8 because readAllBytes is available since JDK9
Author   wvlet
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Program Creek
programcreek.com › java-api-examples
Java Code Examples for java.io.InputStream#readAllBytes()
@Test @Ignore public void write() throws Exception { Body body = new Body(BodyType.binary, null, ""); byte[] data = new byte[1024]; for (int i = 0; i < data.length; i++) { data[i] = (byte) i; } for (int i = 0; i < 520; i++) { body.append(ByteBuffer.wrap(data)); } body.finish(); InputStream inputStream = body.getDecodedInputStream(); byte[] bytes = inputStream.readAllBytes(); assertEquals(520 * 1024, bytes.length); } ... private static byte[] readTestClassBytes() { try { String classFileName = "jdk/jfr/event/oldobject/TestClassLoader$TestClass0000000.class"; InputStream is = TestClassLoader.class.getClassLoader().getResourceAsStream(classFileName); if (is == null) { throw new RuntimeException("Culd not find class file " + classFileName); } byte[] b = is.readAllBytes(); is.close(); return b; } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException(ioe); } }
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › io › InputStream.html
InputStream (Java SE 9 & JDK 9 )
Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input. ... BufferedInputStream, ByteArrayInputStream, DataInputStream, FilterInputStream, read(), OutputStream, PushbackInputStream · clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
🌐
GitHub
github.com › AdoptOpenJDK › openjdk-jdk11 › blob › master › src › java.base › share › classes › java › io › InputStream.java
openjdk-jdk11/src/java.base/share/classes/java/io/InputStream.java at master · AdoptOpenJDK/openjdk-jdk11
* Returns a new {@code InputStream} that reads no bytes. The returned · * stream is initially open. The stream is closed by calling the · * {@code close()} method. Subsequent calls to {@code close()} have no · * effect. * * <p> While the stream is open, the {@code available()}, {@code read()}, * {@code read(byte[])}, {@code read(byte[], int, int)}, * {@code readAllBytes()}, {@code readNBytes(byte[], int, int)}, * {@code readNBytes(int)}, {@code skip(long)}, and ·
Author   AdoptOpenJDK
🌐
Stack Overflow
stackoverflow.com › questions › 61542461 › java-datainputstream-readallbytes-empty
tcp - Java DataInputStream readAllBytes empty? - Stack Overflow
May 1, 2020 - But it seems that it may be stuck at System.out.println(in.readAllBytes());. Im using Java 9 and readAllBytes should be in InputStream.java ... Ok, that is clearer. readAllBytes is new in Java 9. The documentation says it will read until an end of stream is detected. That means until the stream is closed on the sending side. ... If you're going to be keeping the connections open for a bit, you might want to not close the stream each time.
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.io.inputstream.readallbytes
InputStream.ReadAllBytes Method (Java.IO) | Microsoft Learn
The behavior for the case where the input stream is asynchronously closed, or the thread interrupted during the read, is highly input stream specific, and therefore not specified.
Top answer
1 of 4
9

Usually I prefer using a fixed size buffer when reading from input stream. As evilone pointed out, using available() as buffer size might not be a good idea because, say, if you are reading a remote resource, then you might not know the available bytes in advance. You can read the javadoc of InputStream to get more insight.

Here is the code snippet I usually use for reading input stream:

byte[] buffer = new byte[BUFFER_SIZE];

int bytesRead = 0;
while ((bytesRead = in.read(buffer)) >= 0){
  for (int i = 0; i < bytesRead; i++){
     //Do whatever you need with the bytes here
  }
}

The version of read() I'm using here will fill the given buffer as much as possible and return number of bytes actually read. This means there is chance that your buffer may contain trailing garbage data, so it is very important to use bytes only up to bytesRead.

Note the line (bytesRead = in.read(buffer)) >= 0, there is nothing in the InputStream spec saying that read() cannot read 0 bytes. You may need to handle the case when read() reads 0 bytes as special case depending on your case. For local file I never experienced such case; however, when reading remote resources, I actually seen read() reads 0 bytes constantly resulting the above code into an infinite loop. I solved the infinite loop problem by counting the number of times I read 0 bytes, when the counter exceed a threshold I will throw exception. You may not encounter this problem, but just keep this in mind :)

I probably will stay away from creating new byte array for each read for performance reasons.

2 of 4
7

read() will return -1 when the InputStream is depleted. There is also a version of read which takes an array, this allows you to do chunked reads. It returns the number of bytes actually read or -1 when at the end of the InputStream. Combine this with a dynamic buffer such as ByteArrayOutputStream to get the following:

InputStream in = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int read;
byte[] input = new byte[4096];
while ( -1 != ( read = in.read( input ) ) ) {
    buffer.write( input, 0, read );
}
input = buffer.toByteArray()

This cuts down a lot on the number of methods you have to invoke and allows the ByteArrayOutputStream to grow its internal buffer faster.

🌐
Stack Overflow
stackoverflow.com › questions › 45619545 › why-doesnt-inputstream-read-read-all-bytes
java - Why doesn't InputStream.read() read all bytes? - Stack Overflow
The class Server's InputStream is not reading all the bytes sent from class Clients's OutputStream and as a result it's stuck in the while((read = is.read()) != -1) loop because the stream never returned -1.
🌐
Stack Overflow
stackoverflow.com › questions › 70101012 › cannot-invoke-java-io-inputstream-readallbytes-because-the-return-value-of
html - Cannot invoke "java.io.InputStream.readAllBytes()" because the return value of "java.lang.Class.getResourceAsStream(String)" is null - Stack Overflow
Now I want to get the JavaScript resource out of the HTML by using · private String readFileAsTextUsingInputStream(String filename) { if(Objects.equals(filename, "/login")) { filename = "/Users/myName/Desktop/Arbeit/Lehrerkalender/src/main/resources/html/login.html"; } return Connection.class.getResourceAsStream(filename).readAllBytes().toString(); }
🌐
Stack Overflow
stackoverflow.com › questions › 70632483 › calling-readallbytes-on-an-inputstream-of-a-process-returns-empty-byte-array
java - Calling readAllBytes on an InputStream of a process returns empty byte array - Stack Overflow
January 8, 2022 - public class Test { public static void main(String[] args) throws IOException { Process p = Runtime.getRuntime().exec("tput cols"); String output = new String(p.getInputStream().readAllBytes()); System.out.println(output); } } But it outputs empty string. However, if I executes it in the terminal I can see the output. ... For the record, this works fine for me. How are you running it? If I run it from a terminal then I get the same value back that I get from just running tput cols if you run it from something that doesn't provide a terminal you might not get the expected results.
🌐
Stack Overflow
stackoverflow.com › questions › 63855541 › having-trouble-getting-readallbytes-method-to-work
java - Having trouble getting readAllBytes() method to work - Stack Overflow
I am trying to use the readAllBytes() method for an assignment and I can't get it to work. My teacher there is another way he intended it to work using That method is not defined for DataInputStream. Take a look at the read(byte[]) method and the first integer in the datastream shows how large the byte Array is. Either way will work, I just am getting an error on line 39, and if I delete "import java.io.DataInputStream;" it fixes that error but I get an error on line 31 instead.
🌐
TutorialsPoint
tutorialspoint.com › article › when-to-use-the-readallbytes-method-of-inputstream-in-java-9
When to use the readAllBytes() method of InputStream in Java 9?
June 12, 2025 - The reallAllBytes() method can't automatically close the InputStream instance. When it reaches the end of a stream, the further invocations of this method can return an empty byte array. We can use this method for simple use cases where it is convenient to read all bytes into a byte array, and not intended for reading input streams with a large amount of data.
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-8194957
new method InputStream.readAllBytes(int n) to read up to n ...
* * @param len the maximum number of bytes to read * @return a byte array containing the bytes read from this input stream * @throws IndexOutOfBoundsException if {@code length} is negative * @throws IOException if an I/O error occurs * @throws OutOfMemoryError if an array of the required size cannot be * allocated. For example, if an array larger than {@code 2GB} would * be required to store the bytes. * * @since 11 */ public byte[] readAllBytes(int len) throws IOException {}
🌐
GitHub
github.com › AdoptOpenJDK › openjdk-jdk11 › blob › master › test › jdk › java › io › InputStream › ReadAllBytes.java
openjdk-jdk11/test/jdk/java/io/InputStream/ReadAllBytes.java at master · AdoptOpenJDK/openjdk-jdk11
* 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA · * or visit www.oracle.com if you need additional information or have any · * questions. */ · import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Random; import jdk.test.lib.RandomFactory; ·
Author   AdoptOpenJDK