Java Reference
In-Depth Information
PushbackInputStream
A PushbackInputStream adds functionality to an input stream that lets you unread bytes (or push back the read bytes)
using its unread() method. There are three versions of the unread() method. One lets you push back one byte and
other two let you push back multiple bytes. If you call the read() method on the input stream after you have called
its unread() method, you will first read those bytes that you have pushed back. Once all unread bytes are read again,
you start reading fresh bytes from the input stream. For example, suppose your input stream contains a string of bytes,
HELLO . If you read two bytes, you would have read HE . If you call unread((byte)'E') to push back the last byte you
have read, the subsequent read will return E and the next reads will read LLO.
Listing 7-18 illustrates how to use the PushbackInputStream to unread bytes to the input stream and reread
them. This example reads the first stanza of the poem Lucy by William Wordsworth from the luci1.txt in the current
working directory. It reads each byte from the file twice as shown in the output. For example, STRANGE is read as
SSTTRRAANNGGEE . You may notice a blank line between two lines because each new line is read twice.
Listing 7-18. Using the PushbackInputStream Class
// PushbackFileReading.java
package com.jdojo.io;
import java.io.PushbackInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class PushbackFileReading {
public static void main(String[] args) {
String srcFile = "luci1.txt";
try (PushbackInputStream pis = new PushbackInputStream(
new FileInputStream(srcFile))) {
// Read one byte at a time and display it
byte byteData;
while ((byteData = (byte) pis.read()) != -1) {
System.out.print((char) byteData);
// Unread the last byte that we have just read
pis.unread(byteData);
// Reread the byte we unread (or pushed back)
byteData = (byte) pis.read();
System.out.print((char) byteData);
}
}
catch (FileNotFoundException e1) {
FileUtil.printFileNotFoundMsg(srcFile);
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
 
Search WWH ::




Custom Search