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 OverflowGitHub
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
import java.util.Random; import jdk.test.lib.RandomFactory; · /* * @test · * @bug 8080835 8193832 · * @library /test/lib · * @build jdk.test.lib.RandomFactory · * @run main ReadAllBytes · * @summary Basic test for InputStream.readAllBytes · * @key randomness ·
Author AdoptOpenJDK
Top answer 1 of 2
15
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);
2 of 2
9
You can use the good old read method like this:
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
final int bufLen = 1024;
byte[] buf = new byte[bufLen];
int readLen;
IOException exception = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
outputStream.write(buf, 0, readLen);
return outputStream.toByteArray();
} catch (IOException e) {
exception = e;
throw e;
} finally {
if (exception == null) inputStream.close();
else try {
inputStream.close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
}
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › io › ByteArrayInputStream.html
ByteArrayInputStream (Java SE 11 & JDK 11 )
January 20, 2026 - nullInputStream, read, readAllBytes, readNBytes, readNBytes, transferTo · clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait · protected byte[] buf · An array of bytes that was provided by the creator of the stream. Elements buf[0] through buf[count-1] ...
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › io › InputStream.html
InputStream (Java SE 11 & JDK 11 )
January 20, 2026 - Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input · While the stream is open, the available(), read(), read(byte[]), read(byte[], int, int), readAllBytes(), readNBytes(byte[], int, int), readNBytes(int), skip(long), ...
Mkyong
mkyong.com › home › java › how to read a file in java
How to read a file in Java - Mkyong.com
July 17, 2020 - Files.readString, returns a String (Java 11), max file size 2G. Files.readAllBytes, returns a byte[] (Java 7), max file size 2G.
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.
Linux Hint
linuxhint.com › java-input-stream-read-all-bytes
Linux Hint – Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
GitHub
github.com › AdoptOpenJDK › openjdk-jdk11 › blob › master › src › java.base › share › classes › java › io › ByteArrayInputStream.java
openjdk-jdk11/src/java.base/share/classes/java/io/ByteArrayInputStream.java at master · AdoptOpenJDK/openjdk-jdk11
March 2, 2019 - public synchronized byte[] readAllBytes() { byte[] result = Arrays.copyOfRange(buf, pos, count); pos = count; return result; } · public int readNBytes(byte[] b, int off, int len) { int n = read(b, off, len); return n == -1 ?
Author AdoptOpenJDK
Top answer 1 of 16
1517
From JDK 7 you can use Files.readAllBytes(Path).
Example:
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
2 of 16
584
It depends on what best means for you. Productivity wise, don't reinvent the wheel and use Apache Commons. Which is here FileUtils.readFileToByteArray(File input).
Mkyong
mkyong.com › home › java › java files.readallbytes example
Java Files.readAllBytes example - Mkyong.com
April 8, 2019 - package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; public class FileExample2 { public static void main(String[] args) { byte[] bytes = {1, 2, 3, 4, 5}; // Write into binary format try { Files.write(Paths.get("app.bin"), bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException x) { System.err.format("IOException: %s%n", x); } // Read try { byte[] content = Files.readAllBytes(Paths.get("app.bin")); // for binary System.out.println(Arrays.toString(content)); } catch (IOException e) { e.printStackTrace(); } } }
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - In Java, we can use `Files.readAllBytes(path)` to convert a `File` object into a `byte[]`.
Baeldung
baeldung.com › home › java › java io › java inputstream to string
Java InputStream to String | Baeldung
January 5, 2024 - @Test public void givenUsingJava9_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException { String originalString = randomAlphabetic(DEFAULT_SIZE); InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); String text = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); assertThat(text, equalTo(originalString)); } We need to be aware that this simple code is intended for simple cases where it’s convenient to read all bytes into a byte array. We shouldn’t use it for reading input streams with large amounts of data. Next, let’s look at a plain Java example using a standard text Scanner: