Introduction
The push back input stream is a class used to unread data, to push back byte data into stream. The main functionality of this is to interpret the present byte into the stream.
If the unread() method is called then, it pushes the data into the push back input stream. After again calling read() method at that time the push backed data will reads first. The last pushed byte data will be reads first. The push back data limit is also initialized with constructor in push back input stream.
Examples
Usage of void unread(byte b) method.
[c]import java.io.*;
public class PushbackInputStream
{
public static void main(String[] args)
{
// To declare the buffer and initialize its size:
byte[] arrByte = new byte[1024];
// creating a new byte array
byte[] byteArray = new byte[]{'H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D'};
// creating a new PushbackInputStream instance for specified stream
InputStream is = new ByteArrayInputStream(byteArray);
PushbackInputStream pis = new PushbackInputStream(is, 10);
try {
// To read from the buffer one character at a time
for (int i = 0; i < byteArray.length; i++) {
// To read a char into our array
arrByte[i] = (byte) pis.read();
// To display the read byte
System.out.println((char) arrByte[i]);
}
// creating a new byte array to be unread
byte[] b = {'S', 'P', 'L', 'E', 'S', 'S', 'O', 'N', 'S', '.'};
// To unread the byte array
pis.unread(b);
// TO read again from the buffer one character at a time
for (int i = 0; i < byteArray.length; i++) {
// To read a char into array
arrByte[i] = (byte) pis.read();
// To display the byte reads
System.out.print((char) arrByte[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}[/c]
Output
Following is the result will be displayed.
[c]
HELLOWORLD
SPLESSONS.[/c]
Usage of void unread(byte[] b, int off, int n) method.
[c]import java.io.*;
public class PushbackInputStream
{
public static void main(String[] args)
{
// To declare a buffer and initialize its size:
byte[] arrByte = new byte[1024];
// creating a new byte array
byte[] byteArray = new byte[]{'H', 'e', 'l', 'l', 'o'};
// creating a new PushbackInputStream instance for specified stream
InputStream is = new ByteArrayInputStream(byteArray);
PushbackInputStream pis = new PushbackInputStream(is);
try {
// To read from the buffer one character at a time
for (int i = 0; i < byteArray.length; i++) {
// To read a char into array
arrByte[i] = (byte) pis.read();
// To display the byte read
System.out.print((char) arrByte[i]);
}
System.out.println("\n");
// To close the stream
pis.close();
System.out.println("Stream closed.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}[/c]
Output
Following is the result will be displayed.
[c]
Hello
Stream closed.
[/c]