Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java FileInputStream read() Method

In this tutorial, we will learn about the read() method of the FileInputStream class in Java. This method is used to read a byte of data from the current input stream. It blocks if no input is available. It is a non-static method, available in the java.io package.

Syntax

This is the syntax declaration of this method. It does not accept any parameters and it returns the next byte of data or -1 if the end of the file is reached.

public int read()

Example 1: Read bytes of Data in Java

In this example, we are using read() method of FileInputStream class to read byte from the input stream. See the example below.

package com.studytonight;

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 
      {
         fis = new FileInputStream("E://studytonight//output.txt");
         
         while((i = fis.read())!=-1) {
            c = (char)i;
            
            System.out.print(c);
         }
         
      } 
      catch(Exception e) 
      {
         System.out.println("Error: "+e.toString());
      }  
   }
}

Output.txt

Hello Studytonight


Hello Studytonight

Example 2: Read bytes of Data in Java

This is another example to understand the use of read() method of FileInputStream class. See the example below.

import java.io.FileInputStream;

public class Main {

  public static void main(String args[]) {

     try {
        FileInputStream input = new FileInputStream("E://studytonight//input.txt");

        System.out.println("Data in the file: ");

        // Reads the first byte
        int i = input.read();

       while(i != -1) {
           System.out.print((char)i);

           // Reads next byte from the file
           i = input.read();
        }
        input.close();
     }

     catch(Exception e) {
        e.getStackTrace();
     }
  }
}

input.txt

Let's be studytonight curious 


Data in the file:
Let's be studytonight curious

Conclusion

In this tutorial, we learned about the read() method of the FileInputStream class in Java. which reads the next byte of data from the current input stream and returns it. It is accessible with the class object only and if we try to access the method with the class name then we will get an error.