The PushbackInputStream class in Java is used to read data from an input stream with the ability to push back bytes that have already been read.
In this chapter, we will understand what the PushbackInputStream class is, why it is used, its declaration, constructors, important methods, and how unread functionality works using an example.
The PushbackInputStream class extends FilterInputStream and provides additional functionality to another input stream. It allows a program to unread one or more bytes after they have been read.
This feature is useful when a program needs to inspect input data and then decide whether to process it or push it back for re-reading later. It is commonly used in parsing scenarios.
The following declaration shows how the PushbackInputStream class is defined:
The PushbackInputStream class provides constructors to create a pushback buffer.
This constructor creates a PushbackInputStream with a default pushback buffer size of one byte.
Syntax:
Here is the syntax:
This constructor creates a PushbackInputStream with a specified pushback buffer size.
Syntax:
Here is the syntax:
The following example shows how the constructor of the PushbackInputStream class is used.
The PushbackInputStream class provides the following methods to read and unread bytes.
| Method | Description |
|---|---|
| int available() | It is used to return the number of bytes that can be read from the input stream. |
| int read() | It is used to read the next byte of data from the input stream. |
| boolean markSupported() | |
| void mark(int readlimit) | It is used to mark the current position in the input stream. |
| long skip(long x) | It is used to skip over and discard x bytes of data. |
| void unread(int b) | It is used to pushes back the byte by copying it to the pushback buffer. |
| void unread(byte[] b) | It is used to pushes back the array of byte by copying it to the pushback buffer. |
| void reset() | It is used to reset the input stream. |
| void close() | It is used to close the input stream. |
Practice the following examples to understand the methods and usages of PushbackInputStream class.
The following example demonstrates how to unread bytes and replace specific characters using the PushbackInputStream class.
Output:
1**2#34**#12
The following example demonstrates how a byte can be read, checked, and then pushed back into the stream if required.
Output:
Read character: A Re-read character: A
We request you to subscribe our newsletter for upcoming updates.