Java.io.InputStream.read() Method


Advertisements


Description

The java.io.InputStream.read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255. If no byte is available because the end of the stream has been reached, the returned value is -1.

Declaration

Following is the declaration for java.io.InputStream.read() method −

public abstract int read()

Parameters

NA

Return Value

This method returns the next byte of data, or -1 if the end of the stream is reached.

Exception

IOException − If an I/O error occurs.

Example

The following example shows the usage of java.io.InputStream.read() 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;
      int i;
      char c;
      
      try {
      
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         System.out.println("Characters printed:");
         
         // reads till the end of the stream
         while((i = is.read())!=-1) {
         
            // converts integer to character
            c = (char)i;
            
            // 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

java_io_inputstream.htm

Advertisements