When to use the readAllBytes() method of InputStream in Java 9?

JavaObject Oriented ProgrammingProgramming

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"
raja
Published on 28-Feb-2020 19:23:12
Advertisements