✅ What Is PushbackInputStream
?
PushbackInputStream
is a special kind of InputStream
that allows you to “unread” or push back bytes into the stream — so they can be read again later.
It’s like a stream with an “undo” buffer — ideal for building parsers or tokenizers.
🔧 Main Use Case
Used when you’re reading ahead, and based on what you see, you want to put some bytes back because they belong to the next token or need to be reprocessed.
🧪 Example Use Case: Custom Parser
Let’s say you’re parsing text and you read a byte that doesn’t belong to the current token. You can push it back:
import java.io.*;
public class PushbackExample {
public static void main(String[] args) throws IOException {
byte[] data = "123X456".getBytes();
try (PushbackInputStream in = new PushbackInputStream(new ByteArrayInputStream(data))) {
int ch;
while ((ch = in.read()) != -1) {
if (ch == 'X') {
System.out.println("Found X — push it back!");
in.unread(ch); // push it back
break;
}
System.out.print((char) ch);
}
System.out.println("\nRe-reading after pushback:");
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
}
}
}
🔹 Output:
123
Found X — push it back!
Re-reading after pushback:
X456
🔹 Constructors and Methods
Constructor:
PushbackInputStream(InputStream in, int size);
size
= number of bytes you can push back
Key Method:
void unread(int b) throws IOException;
Pushes one byte back into the stream
🧠 Summary
Feature | Description |
---|---|
Purpose | Allows reading ahead and then backtracking |
Best for | Parsers, tokenizers, interpreters |
Key method | unread() — puts byte(s) back |
Wraps | Any InputStream |