A PushbackInputStream adds functionality to another input stream, namely the ability to “push back” or “unread” one byte.
Please read PushbackReader for Character based counterpart.
The PushbackInputStream is intended to be used when you parse data from an InputStream. Sometimes you need to read ahead a few bytes to see what is coming, before you can determine how to interpret the current byte. The PushbackInputStream allows you to do that. Well, actually it allows you to push the read bytes back into the stream. These bytes will then be read again the next time you call read().
Constructors
Methods
package com.java.io;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
public class PushbackInputStreamExample {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
PushbackInputStream pushbackInputStream = null;
try {
fileInputStream = new FileInputStream("/Test/TestFolder/test-file.txt");
pushbackInputStream = new PushbackInputStream(fileInputStream);
byte b[] = new byte[15];
System.out.print("Content:");
if (pushbackInputStream.available() > 0) {
pushbackInputStream.read(b);
for (int i = 0; i < 15; i++) {
System.out.print((char) b[i]);
}
}
System.out.println("");
System.out.println("PushedBack Character:" + (char) b[0]);
pushbackInputStream.unread(b[0]);
System.out.print("PushedBack Character read again:");
if (pushbackInputStream.available() > 0) {
System.out.print((char) pushbackInputStream.read());
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (fileInputStream != null)
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (pushbackInputStream != null)
try {
pushbackInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Content:Test Data
PushedBack Character:T
PushedBack Character read again:T