Java.io.FileInputStream.read() Method



Description

The java.io.FileInputStream.read() reads a byte of data from this input stream. The method blocks if no input is available.

Declaration

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

public int read()

Parameters

NA

Return Value

The methods returns the next byte of data, or -1 if the end of the file is reached.

Exception

IOException − If an I/O error occurs

Example

The following example shows the usage of java.io.FileInputStream.read() method.

package com.tutorialspoint;

import java.io.IOException;
import java.io.FileInputStream;

public class FileInputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileInputStream fis = null;
      int i = 0;
      char c;
      
      try {
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read till the end of the file
         while((i = fis.read())!=-1) {
         
            // converts integer to character
            c = (char)i;
            
            // prints character
            System.out.print(c);
         }
         
      } catch(Exception ex) {
         // if any error occurs
         ex.printStackTrace();
      } finally {
         // releases all system resources from the streams
         if(fis!=null)
            fis.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 −

ABCDEF

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

ABCDEF
java_io_fileinputstream.htm
Advertisements