
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When to Use the readAllBytes Method of InputStream in Java 9
Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.
The reallAllBytes() method can't automatically close the InputStream instance. When it can reach 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.
Syntax
public byte[] readAllBytes() throws IOException
In the below example, we have created a "Technology.txt" file in a "C:\Temp" folder with simple data: { "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}.
Example
import java.nio.*; import java.nio.file.*; import java.io.*; import java.util.stream.*; import java.nio.charset.StandardCharsets; public class ReadAllBytesMethodTest { public static void main(String args[]) { try(InputStream stream = Files.newInputStream(Paths.get("C://Temp//Technology.txt"))) { // Convert stream to string String contents = new String(stream.readAllBytes(), StandardCharsets.UTF_8); // To print the string content System.out.println(contents); } catch(IOException ioe) { ioe.printStackTrace(); } } }
Output
"JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"