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

Java FilterInputStream read() Method

In this tutorial, we will learn about the read() method of the FilterInputStream 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 From InputStream in Java

In the following example, we are going to read the data from a file. Firstly we created an input stream using FilterInputStream class by passing a file path in a constructor. Then using the read() method we are reading each character one by one till the stream reaches the end. It returns -1 when we reach the end of the stream.

package com.studytonight;

import java.io.IOException;
import java.io.FilterInputStream;

public class studytonight {
   public static void main(String[] args) throws IOException {
      FilterInputStream st = null;
      int i = 0;
      char c;
      
      try
      {
         st = new FilterInputStream("E:/studytonight/output.txt");
         
         while((i = st.read())!=-1) 
         {
         
            c = (char)i;
            
            System.out.print(c);
         }
         
      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }  
   }
}

Output.txt

Hello Studytonight


Hello Studytonight

Example 2: Read Bytes From InputStream in Java

In this example, we read the data from the stream, and then we will print that data. This method reads and returns a byte of data from the current stream.

import java.io.FilterInputStream;

public class StudyTonight{

  public static void main(String args[]) {

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

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

        int i = input.read();

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

           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 FilterInputStream 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.