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
Support ByteStreams.toByteArray -> inputStream.readAllBytes()
Instead of Guava's ByteStreams#toByteArray(), InputStream.html#readAllBytes should be used. The latter is available since Java 9. More on github.com
There are so many Reader classes. Which one should I use to read from a file?
There are 2 axes to think about: What am I reading? Binary or text? If I'm reading binary, use an InputStream. If I'm reading text, use a Reader. A Reader basically wraps an InputStream and handles the conversion from whatever encoding was used to store the text (e.g., UTF-8, ISO-8859-1, etc.) What do I have? If you have a File, use a FileInputStream or FileReader. If you already have an InputStream, use an InputStreamReader. The other thing is that these things "stack". So if you have a File with some text, probably the best thing to do is to create a new BufferedReader(new FileReader(file)) BufferedReader is nice because you can read one line at a time using readLine(). BUT, there's a glitch here, which is that doing it that way doesn't set you specify how text in the file was actually encoded. So what you really need to do is: new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")) Hope that helps. More on reddit.com
Mkyong
mkyong.com › home › java › java files.readallbytes example
Java Files.readAllBytes example - Mkyong.com
April 8, 2019 - In Java, we can use Files.readAllBytes to read a file.
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.
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);
}
}
}
How to do in Java
howtodoinjava.com › home › i/o › read file to byte[] in java
Read File to Byte[] in Java
December 14, 2022 - In Java, reading a file to byte array may be needed in various situations. For example, passing the information through the network and other APIs for further processing. Let’s learn about a few ways of reading data from files into a byte array in Java. The Files.readAllBytes() is the best method for using Java 7, 8 and above.
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 - Below is an example to read content from "Technology.txt" using the readAllBytes() method in Java:
GitHub
github.com › openrewrite › rewrite-migrate-java › issues › 390
Support ByteStreams.toByteArray -> inputStream.readAllBytes() · Issue #390 · openrewrite/rewrite-migrate-java
January 12, 2024 - Instead of Guava's ByteStreams#toByteArray(), InputStream.html#readAllBytes should be used. The latter is available since Java 9. - String inputStr = new String(ByteStreams. toByteArray(inputStream), Charsets.UJTF_8); + String inputStr = new ...
Author openrewrite
Java Tips
javatips.net › api › java.nio.file.files.readallbytes
Java Examples for java.nio.file.Files.readAllBytes - Javatips.net
public static void main(String[] args) throws Exception { // get reference of source/input file java.nio.file.Path path = java.nio.file.Paths.get("input.pdf"); // read all the contents from source file into ByteArray byte[] data = java.nio.file.Files.readAllBytes(path); // create an instance of Stream object from ByteArray contents InputStream is = new ByteArrayInputStream(data); // Instantiate Document object from stream instance Document pdfDocument = new Document(is); // setup new file to be added as attachment FileSpecification fileSpecification = new FileSpecification("test.txt", "Sample text file"); // Specify Encoding property setting it to FileEncoding.None fileSpecification.setEncoding(FileEncoding.None); // add attachment to document's attachment collection pdfDocument.getEmbeddedFiles().add(fileSpecification); // save new output pdfDocument.save("output.pdf"); }
GitHub
github.com › bbossola › vulnerability-java-samples › blob › master › exploit › Encoder.java
vulnerability-java-samples/exploit/Encoder.java at master · bbossola/vulnerability-java-samples
import java.util.Base64; · public class Encoder { · public static void main(String[] args) throws Exception { byte[] classBytes = Files.readAllBytes(new File("Exploit.class").toPath()); byte[] encodedBytes = Base64.getEncoder().encode(classBytes); System.out.println(new String(encodedBytes)); } }
Author bbossola
CalliCoder
callicoder.com › java-read-file
How to read a File in Java | CalliCoder
February 18, 2022 - import com.sun.org.apache.xpath.internal.operations.String; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesReadAllBytesExample { public static void main(String[] args) { try { byte[] data = Files.readAllBytes(Paths.get("demo.txt")); // Use byte data } catch (IOException ex) { System.out.format("I/O error: %s%n", ex); } } } Facebook · Twitter · Linkedin · Reddit · Twitter · Github ·
How to do in Java
howtodoinjava.com › home › i/o › java read file to string (with examples)
Java Read File to String (with Examples)
October 22, 2023 - Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; try { byte[] bytes = Files.readAllBytes(Paths.get(filePath)); fileContent = new String (bytes); } catch (IOException e) { //handle exception } If you are still not using Java ...
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - package com.mkyong.io.howto; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileToBytes { public static void main(String[] args) { try { String filePath = "/home/mkyong/test/phone.png"; // file to bytes[] byte[] bytes = Files.readAllBytes(Paths.get(filePath)); // bytes[] to file Path path = Paths.get("/home/mkyong/test/phone2.png"); Files.write(path, bytes); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } } $ git clone https://github.com/mkyong/core-java ·
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