Java.io.InputStream.read() Method

Advertisements


Description

The java.io.InputStream.read(byte[] b) method reads b.length number of bytes from the input stream to the buffer array b. The bytes read is returned as integer.

Declaration

Following is the declaration for java.io.InputStream.read(byte[] b) method:

public int read(byte[] b)

Parameters

  • b -- The destination byte array.

Return Value

The method returns the number of bytes actually read into the buffer, or -1 if the end of the stream is reached..

Exception

  • IOException -- if an I/O error occurs.

  • NullPointerException -- if b is null.

Example

The following example shows the usage of java.io.InputStream.read(byte[] b) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) throws Exception {
      
      InputStream is = null;
      byte[] buffer=new byte[5];
      char c;
      
      try{
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         System.out.println("Characters printed:");
         
         // read stream data into buffer
         is.read(buffer);
         
         // for each byte in the buffer
         for(byte b:buffer)
         {
            // convert byte to character
            c=(char)b;
            
            // prints character
            System.out.print(c);
         }
      }catch(Exception e){
         
         // if any I/O error occurs
         e.printStackTrace();
      }finally{
         
         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDE

Let us compile and run the above program, this will produce the following result:

Characters printed:
ABCDE



Advertisements
Advertisements