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.txtfile in a "C:\Tempfolder 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"

Updated on: 28-Feb-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements