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

JavaObject Oriented ProgrammingProgramming

Since Java 9, the readNBytes() method can be added to the InputStream class. This method reads the requested number of bytes from an input stream into the given byte array. This method blocks until len bytes of input data have read, end of a stream is detected, or an exception is thrown. The readNBytes() method doesn't close an input stream. This method can be useful to avoid memory problems with large files.


public int readNBytes(byte[] b, int off, int len) throws IOException

In the below example, we have created a "Technology.txt" file in the source folder with simple data: { "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}.


import java.io.*;
import java.util.stream.*;
import java.nio.*;
import java.nio.file.*;

public class InputStreamReadNByteMethodTest {
   InputStream inputStream = nputStreamReadNByteMethodTest.class.getResourceAsStream("Technology.txt");

   public void testReadNBytes() throws Exception {
      final byte[] data = new byte[10];
      inputStream.readNBytes(data, 0, 7);
      System.out.println(new String(data));
   public static void main(String args[]) throws Exception {
      InputStreamReadNByteMethodTest t = new InputStreamReadNByteMethodTest();


Updated on 03-Mar-2020 14:12:22