Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.FilterWriter class in Java
Next article icon

Java.io.FilterInputStream Class in Java

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

FilterInputStream Class in Java

Filter Streams filters data as they read and write data in the Input Stream, filters it and pass it on to the underlying Streams. Filter Streams are

  • FilterInputStream
  • FilterOutput Stream

FilterInputStream : Java.io.FilterInputStream class works almost like InputStream class in Java but what it does is simply overriding the InputStream class methods, passing the request to the InputStream. The read() method of FilterInputStream Class filters the data and read it and passes on the data to the underlying stream filtering which is done depending on the Streams.

Declaration:

  public class FilterInputStream     extends InputStream

Constructors :

  • protected FilterInputStream(InputStream in): Creates a FilterInputStream by assigning the argument in to the field this.in so as to remember it for later use.

Methods:

  • read(byte[] buffer) : java.io.FilterInputStream.read(byte[] buffer) reads number of bytes of buffer.length from the Filter Input Stream to the buffer array.
    Syntax :
      public int read(byte[] buffer)  Parameters :  buffer : buffer to be read  Return :   reads number of bytes of buffer.length to the buffer   else, -1 i.e. when end of file is reached.  Exception :  ->  IOException : If I/O error occurs.
  • Implementation :




    // Java program illustrating the working of read(byte[] buffer) method
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException
        {
            // LineNumberInputStream & FileInputStream initailly null
            FilterInputStream geek_input = null;
            InputStream geek = null;
      
            try{
                char c;
                int a;
                byte[] buffer = new byte[6];
      
                // New InputStream : 'GEEKS' is created
                geek = new FileInputStream("GEEKS.txt");
                geek_input = new BufferedInputStream(geek);
      
                a = geek.read(buffer);
                // read() method returning Bytes of Input Stream as integer
                // '-1' indicating to read till end Of Input Stream
                int length = 1 ;
                  
                for(byte g : buffer)
                {
                    // Since read() method returns Integer value
                    // So, we convert each integer value to char
                    c = (char)g;
      
                    System.out.println("At position " + length  +  " : "  + c);
                    length++;
                }
            }
            catch(Exception e)
            {
                // In case of error
                e.printStackTrace();
                System.out.println("ERROR Occurs ");
            }
            finally
            {
                // Closing the streams, Once the End of Input Stream is reached
                if(geek != null)
                    geek.close();
      
                if(geek_input != null)
                    geek_input.close();
            }
        }
    }
     
     

    Note :
    The following Java Code won’t run here as we can’t access any file on online IDE.
    So, copy the program to your system and run it there.

    The GEEKS.txt file used in the program contains :

HelloGeeks

In the given code buffer.length = 6 , So only HelloG will b read by read(byte[] buffer) method
Output :

  At position 1 : H  At position 2 : e  At position 3 : l  At position 4 : l  At position 5 : o  At position 6 : G
  • read(byte[] buffer, int offset, int maxlen) : java.io.FilterInputStream.read(byte[] buffer, int offset, int maxlen) reads upto maxlen of data from the FilterInputStream into a buffer.
    Syntax :
      public int read(byte[] buffer, int offset, int maxlen)  Parameters :  buffer : Destination buffer  offset : start position to read  maxlen : max. length of bytes to be read  Return :   total no. of bytes to be written else, -1 i.e. when end of Stream is reached.  Exception :  ->  IOException : If I/O error occurs.
  • Implementation :




    // Java program illustrating the working of
    // read(byte[] buffer, int offset, int maxlen) method
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws IOException
        {
            // LineNumberInputStream & FileInputStream initailly null
            FilterInputStream geek_input = null;
            InputStream geek = null;
      
            try{
                char c;
                int a;
                byte[] buffer = new byte[4];
      
                // New InputStream : 'ABC' is created
                geek = new FileInputStream("ABC.txt");
                geek_input = new BufferedInputStream(geek);
      
                // Offset = 1(*), Maxlen = 3 (MOH)
                a = geek.read(buffer, 1, 3);
                // read() method returning Bytes of Input Stream as integer
                // '-1' indicating to read till end Of Input Stream
                 
                for(byte g : buffer)
                {
                    // Since read() method returns Integer value
                    // So, we convert each integer value to char
                    c = (char)g;
      
                    if(g == 0)
                        c = '*';
      
                    System.out.print(c);
                }
            }
            catch(Exception e)
            {
                // In case of error
                e.printStackTrace();
                System.out.println("ERROR Occurs ");
            }
            finally
            {
                // Closing the streams, Once the End of Input Stream is reached
                if(geek != null)
                    geek.close();
      
                if(geek_input != null)
                    geek_input.close();
            }
        }
    }
     
     

    Note :
    The following Java Code won’t run here as we can’t access any file on online IDE.
    So, copy the program to your system and run it there.

    The ABC.txt file used in the program contains :

    MOHIT

    Offset = 1 i.e. * and Maxlen = 3 i.e. MOH
    Output :

      *MOH
  • available() : java.io.FilterInputStream.available() returns the no. of bytes that can be read from the Input Stream.
    Syntax :
      public int available()  Parameters :   -------  Return :   returns the no. of bytes that can be read from the FilterInputStream.  Exception:   IOException : in case I/O error occurs
  • Implementation :




    // Java program illustrating the working of available() method
      
    import java.io.*;
    public class NewClass
    {
        public static void main(String[] args) throws IOException
        {
            // FilterInputStream & FileInputStream initailly null
            FilterInputStream geek_input = null;
      
            InputStream geek = null;
      
            try{
                char c;
                int a, b;
      
                // New InputStream : 'ABC' is created
                geek = new FileInputStream("ABC.txt");
                geek_input = new BufferedInputStream(geek);
      
                while((a = geek_input.read()) != -1)
                {
                    // So, we convert each integer value to char
                    c = (char)a;
      
                    // Use of available method : return no. of bytes that can be read
                    a = geek_input.available();
                    System.out.println(c + " Bytes available : " + a);
      
                }
            }
            catch(Exception e)
            {
                // In case of error
                e.printStackTrace();
                System.out.println("ERROR Occurs ");
            }
            finally
            {
                // Closing the streams, Once the End of FilterInputStream is reached
                if(geek != null)
                    geek.close();
      
                if(geek_input != null)
                    geek_input.close();
            }
        }
    }
     
     

    Note :
    The following Java Code won’t run here as we can’t access any file on online IDE.
    So, copy the program to your system and run it there.

    The ABC.txt file used in the program contains :

    MOHIT

    Output :

      M Bytes available : 4  O Bytes available : 3  H Bytes available : 2  I Bytes available : 1  T Bytes available : 0
  • read() : java.io.FilterInputStream.read() reads next byte of data from the Filter Input Stream. The value byte is returned in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.
    Syntax :
      public int read()  Parameters :  ------  Return :   Reads next data else, -1 i.e. when end of Stream is reached.  Exception :  ->  IOException : If I/O error occurs.
  • close() : java.io.FilterInputStream.close() closes the Filter Input Stream and releases system resources associated with this stream to Garbage Collector.
    Syntax :
      public void close()  Parameters :  ------  Return :   void  Exception :  ->  IOException : If I/O error occurs.
  • mark(int arg) : java.io.FilterInputStream.mark(int arg) marks the current position of the FilterInputStream. It sets readlimit i.e. maximum number of bytes that can be read before mark position becomes invalid.
    Syntax :
      public void mark(int arg)  Parameters :  arg : integer specifying the read limit of the input Stream  Return :   void
  • skip() : java.io.FilterInputStream.skip(long arg) skips and discards ‘arg’ bytes from FilterInputStream data.
    Syntax :
      public long skip(long arg)  Parameters :   arg : no. of bytes of FilterInputStream data to skip.  Return :   no. of bytes to be skipped  Exception:   IOException : in case I/O error occurs
  • reset() : java.io.FilterInputStream.reset() is invoked by mark() method. It repositions the FilterInputStream to the marked position.
    Syntax :
      public void reset()  Parameters :  ----  Return :   void  Exception :  ->  IOException : If I/O error occurs.
  • markSupported() : java.io.FilterInputStream.markSupported() method tests if this input stream supports the mark and reset methods. The markSupported method of InputStream returns false by default.
    Syntax :
      public boolean markSupported()  Parameters :  -------  Return :   true if input stream supports the mark() and reset() method  else,false
  • Java Program explaining : markSupported(), close(), reset(), mark(), read(), skip() methods




    // Java program illustrating the working of FilterInputStream method
    // mark(), read(), skip()
    // markSupported(), close(), reset()
      
    import java.io.*;
      
    public class NewClass
    {
        public static void main(String[] args) throws Exception
        {
            InputStream geek = null;
            // FilterInputStream initialised to null here
            FilterInputStream geek_input = null;
            try {
      
                geek = new FileInputStream("GEEKS.txt");
                  
            geek_input = new BufferedInputStream(geek);
      
                // read() method : reading and printing Characters
                // one by one
                System.out.println("Char : " + (char)geek_input.read());
                System.out.println("Char : " + (char)geek_input.read());
                System.out.println("Char : " + (char)geek_input.read());
      
                // mark() : read limiing the 'geek' input stream
                geek_input.mark(0);
      
                // skip() : it results in redaing of 'e' in G'e'eeks
                geek_input.skip(1);
                System.out.println("skip() method comes to play");
                System.out.println("mark() method comes to play");
                System.out.println("Char : " + (char)geek_input.read());
                System.out.println("Char : " + (char)geek_input.read());
                System.out.println("Char : " + (char)geek_input.read());
      
                boolean check = geek_input.markSupported();
                if (geek_input.markSupported())
                {
                    // reset() method : repositioning the stream to
                    // marked positions.
                    geek_input.reset();
                    System.out.println("reset() invoked");
                    System.out.println("Char : " + (char)geek_input.read());
                    System.out.println("Char : " + (char)geek_input.read());
                }
                else
                    System.out.println("reset() method not supported.");
                    System.out.println("geek_input.markSupported() supported" 
                                                    + " reset() : " + check);
      
            }
            catch(Exception excpt)
            {
                // in case of I/O error
                excpt.printStackTrace();
            }
            finally
            {
                // releasing the resources back to the
                // GarbageCollector when closes
                if (geek != null)
                { // Use of close() : closing the file
                    // and releasing resources
                    geek.close();
                }
      
                if(geek_input != null)
                    geek_input.close();
            }
        }
    }
     
     

    Note :
    This code won’t run on online IDE as no such file is present here.
    You can run this code on your System to check the working.
    GEEKS.txt file used in the code has

    HelloGeeks

    Output :

      Char : H  Char : e  Char : l  skip() method comes to play  mark() method comes to play  Char : o  Char : G  Char : e  reset() invoked  Char : l  Char : o  geek_input.markSupported() supported reset() : true


    Next Article
    Java.io.FilterWriter class in Java

    M

    Mohit Gupta
    Improve
    Article Tags :
    • Java
    • Java-I/O
    Practice Tags :
    • Java

    Similar Reads

    • Java.io.FilterOutputStream Class in Java
      java.io.FilterInputStream Class in Java Java.io.FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams. Decla
      5 min read
    • Java.io.InputStream Class in Java
      Java InputStream class is the superclass of all the io classes i.e. representing an input stream of bytes. It represents an input stream of bytes. Applications that are defining a subclass of the Java InputStream class must provide a method, that returns the next byte of input. A reset() method is i
      3 min read
    • Java.io.FilterReader class in Java
      Abstract class for reading filtered character streams. The abstract class FilterReader itself provides default methods that pass all requests to the contained stream. Subclasses of FilterReader should override some of these methods and may also provide additional methods and fields. Constructor : pr
      3 min read
    • Java.io.FilterWriter class in Java
      Abstract class for writing filtered character streams. The abstract class FilterWriter itself provides default methods that pass all requests to the contained stream. Subclasses of FilterWriter should override some of these methods and may also provide additional methods and fields. Constructor : pr
      2 min read
    • Java.io.DataInputStream class in Java | Set 1
      A data input stream enables an application to read primitive Java data types from an underlying input stream in a machine-independent way(instead of raw bytes). That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes. An application uses a data output stream
      3 min read
    • Java.io.DataInputStream class in Java | Set 2
      Java.io.DataInputStream class in Java | Set 1 More Methods: byte readByte() : Reads and returns one input byte. Syntax:public final byte readByte() throws IOException Returns: the next byte of this input stream as a signed 8-bit byte. Throws: EOFException IOException float readFloat() : Reads four i
      3 min read
    • Java.util.zip.DeflaterInputStream class in Java
      Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input
      3 min read
    • Java FileInputStream Class
      FileInputStream class in Java is useful for reading data from a file in the form of a Java sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Example: FileInputStream class to read data from f
      4 min read
    • Java.io.DataOutputStream in Java
      A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in. Let us do discuss the constructor of this class prior to moving ahead to the methods of this class. Constructor: D
      5 min read
    • Java.util.zip.GZIPInputStream class in Java
      This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Meth
      2 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences