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.ObjectInputStream Class in Java | Set 1
Next article icon

Java.io.PushbackInputStream class in Java

Last Updated : 14 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Pushback is used on an input stream to allow a byte to be read and then returned (i.e, “pushed back”) to the stream. The PushbackInputStream class implements this idea. It provides a mechanism “peek” at what is coming from an input stream without disrupting it. 
It extends FilterInputStream.
Fields: 

  • protected byte[] buf:This is the pushback buffer. 
     
  • protected int pos – This is the position within the pushback buffer from which the next byte will be read. 
     
  • protected InputStream in – This is the input stream to be filtered. 

Constructors: 

  • PushbackInputStream(InputStream in): This creates a stream object that allows one byte to be returned to the input stream. 
     
  • PushbackInputStream(InputStream in, int numBytes): This creates a stream that has a pushback buffer that is numBytes long. This allows multiple bytes to be returned to the input stream. 

Methods: 

  • int available(): Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block but may read or skip fewer bytes. 
     
Syntax: public int available() Returns: the number of bytes that can be read  (or skipped over) from the input stream without blocking. Exception: IOException - if this input stream has  been closed by invoking its close() method, or an I/O error occurs.
  • void close(): Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), unread(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect. 
Syntax: public void close() Returns: NA Exception: IOException - if an I/O error occurs.
  • boolean markSupported(): Tests if this input stream supports the mark and reset methods, which it does not. 
Syntax: public boolean markSupported() Returns: false, since this class does not support the mark and reset methods. Exception: NA

Java




// java code illustrating unread() method
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
 
 
public class PushbackInputStreamDemo
{
    public static void main(String arg[]) throws Exception
    {
        PrintWriter pw = new PrintWriter(System.out, true);
        String str = "GeeksforGeeks a computer science portal ";
        byte b[] = str.getBytes();
        ByteArrayInputStream bout = new ByteArrayInputStream(b);
        PushbackInputStream push = new PushbackInputStream(bout);
         
 
      // unread method
        push.unread('A');
        b[1] = (byte)push.read();
        pw.println((char)b[1]);
    }
}
 
 

Output: 

available bytes: 10 mark supported? :false
  • int read(): Reads the next byte of data from this input stream. The value byte is returned as an int 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. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. 
Syntax: public int read() Returns: the next byte of data, or -1 if  the end of the stream has been reached. Exception: IOException - if this input stream  has been closed by invoking its close() method, or an I/O error occurs.
  • int read(byte[] b, int off, int len): Reads up to len bytes of data from this input stream into an array of bytes. This method first reads any pushed-back bytes; after that, if fewer than len bytes have been read then it reads from the underlying input stream. If len is not zero, the method blocks until at least 1 byte of input is available; otherwise, no bytes are read and 0 is returned. 
Syntax: public int read(byte[] b, int off, int len). Returns: the total number of bytes read into  the buffer, or -1 if there is no more data because the end of  the stream has been reached. Exception:  NullPointerException - If b is null. IndexOutOfBoundsException - If off is negative, len is negative, or  len is greater than b.length - off IOException - if this input stream has been closed by invoking its  close() method, or an I/O error occurs.

Java




 
 

Output: 

GeeksforGeeks a computer science portal  GeeksforGeeks
  • void mark(int readlimit): Marks the current position in this input stream. 
    The mark method of PushbackInputStream does nothing. 
Syntax: public void mark(int readlimit) Returns: NA Exception: NA
  • void reset(): Repositions this stream to the position at the time the mark method was last called on this input stream. 
    The method reset for class PushbackInputStream does nothing except throw an IOException. 
Syntax: public void reset() Returns: NA Exception: IOException - if this method is invoked.

Java




// Java code illustrating mark() and reset() method
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
 
 
public class PushbackInputStreamDemo
{
    public static void main(String arg[]) throws Exception
    {
        PrintWriter pw = new PrintWriter(System.out, true);
        String str = "GeeksforGeeks a computer science portal ";
        byte b[] = str.getBytes();
        ByteArrayInputStream bout = new ByteArrayInputStream(b);
        PushbackInputStream push = new PushbackInputStream(bout);
         
        int c;
        while((c=push.read())!=-1)
        {
            pw.print((char)c);
        }
        pw.println();
         
        // marking the position
        push.mark(5);
         
        // resetting is not supported throw exception
        push.reset();
         
        pw.close();
    }
}
 
 

Output: 

GeeksforGeeks a computer science portal  Exception in thread "main" java.io.IOException: mark/reset not supported     at java.io.PushbackInputStream.reset(PushbackInputStream.java:364)     at PushbackInputStreamDemo.main(PushbackInputStreamDemo.java:29)
  • void unread(byte[] b): Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth. 
Syntax: public void unread(byte[] b) returns: NA Exception: IOException - If there is not enough room in  the pushback buffer for the specified number of bytes, or this input  stream has been closed by invoking its close() method.
  • void unread(byte[] b,int off,int len): Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth. 
Syntax: public void unread(byte[] b,int off,int len) Returns: NA Exception: IOException - If there is not enough room  in the pushback buffer for the specified number of bytes, or this input  stream has been closed by invoking its close() method.

Java




// Java code illustrating unread() method
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
 
 
public class PushbackInputStreamDemo
{
    public static void main(String arg[]) throws Exception
    {
        PrintWriter pw = new PrintWriter(System.out, true);
        String str = "GeeksforGeeks a computer science portal ";
        byte b[] = str.getBytes();
        ByteArrayInputStream bout = new ByteArrayInputStream(b);
        PushbackInputStream push = new PushbackInputStream(bout);
         
        int c;
        while((c=push.read())!=-1)
        {
            pw.print((char)c);
        }
        pw.println();
 
      // unread method
        push.unread(b);
        push.unread(b, 0, 6);
 
        while((c=push.read())!=-1)
        {
            pw.print((char)c);
        }
        pw.println();
        pw.close();
    }
}
 
 

Output: 

GeeksforGeeks a computer science portal orGeeks a computer science portal
  • void unread(int b): Pushes back a byte by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value (byte)b. 
Syntax: public void unread(int b) Returns: NA Exception: IOException - If there is not enough  room in the pushback buffer for the byte, or this input stream  has been closed by invoking its close() method.

Java




// java code illustrating unread() method
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
 
 
public class PushbackInputStreamDemo
{
    public static void main(String arg[]) throws Exception
    {
        PrintWriter pw = new PrintWriter(System.out, true);
        String str = "GeeksforGeeks a computer science portal ";
        byte b[] = str.getBytes();
        ByteArrayInputStream bout = new ByteArrayInputStream(b);
        PushbackInputStream push = new PushbackInputStream(bout);
         
 
      // unread method
        push.unread('A');
        b[1] = (byte)push.read();
        pw.println((char)b[1]);
    }
}
 
 

Output: 

A


Next Article
Java.io.ObjectInputStream Class in Java | Set 1
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Java
  • Java-I/O
Practice Tags :
  • Java

Similar Reads

  • Java.io.PipedInputStream class in Java
    Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are used both as source or destination. PipedInputStream is also piped with PipedOutputStream. So, data can be written using PipedOutputStream and can be written using PipedInputStream.But, using both threads
    5 min read
  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
  • Java.io.LineNumberInputStream Class in Java
    java.io.LineNumberInputStream class is simply an extension of input stream providing a extra facility to keep the record of current line number. Line is a sequence of bytes ending with : '\r' i.e. a carriage return character or a newline character : '\n', or a linefeed character following the carria
    11 min read
  • Java.io.ObjectInputStream Class in Java | Set 1
    ObjectInputStream Class deserializes the primitive data and objects previously written by ObjectOutputStream. Both ObjectOutputStream and ObjectInputStream are used as it provides storage for graphs of object.It ensures that the object it is working for, matches the classes of JVM i.e Java Virtual M
    9 min read
  • Java.io.ObjectInputStream Class in Java | Set 2
    Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStrea
    6 min read
  • Java.io.Printstream Class in Java | Set 2
    Java.io.Printstream Class in Java | Set 1More Methods: PrintStream printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this output stream using the specified format string and arguments. Syntax :public PrintStream printf(Locale l, String format, Obje
    6 min read
  • Java.io.Printstream Class in Java | Set 1
    A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the c
    5 min read
  • Java.io.ObjectOutputStream Class in Java | Set 1
    An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. Only objects that support the java.io.Serializable in
    9 min read
  • Java.io.SequenceInputStream in Java
    The SequenceInputStream class allows you to concatenate multiple InputStreams. It reads data of streams one by one. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of fil
    3 min read
  • Java.io.StringReader class in Java
    StringReader class in Java is a character stream class whose source is a string. It inherits Reader Class. Closing the StringReader is not necessary, it is because system resources like network sockets and files are not used. Let us check more points about StringReader Class in Java. Declare StringR
    4 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