If you are a C or C++ programmer, you may familiar withe ungetc
function in C. ungetc function is a very simple but useful function especially when your program need to read characters from a FILE
stream for data parsing. You may encounter cases where you need to unread the character so that you can use that character when you pass in the FILE
reference into another function.
From C manual for ungetc
:
A character is virtually put back into an input stream, decreasing its internal file position as if a previous getc operation was undone.
This character may or may not be the one read from the stream in the preceding input operation. In any case, the next character retrieved from stream is the character passed to this function, independently of the original one.
Notice though, that this only affects further input operations on that stream, and not the content of the physical file associated with it, which is not modified by any calls to this function.
This is my simple version of ungetc
in Java, UInputStream
. I use an InputStream as the base class so that you can work with other input stream object like FileInputStream
. UInputStream
will override the read()
function from InputStream
and an additional function to undone the read.
import java.io.IOException; import java.io.InputStream; public class UInputStream extends InputStream { private InputStream uIn; private boolean uPushedBack; private int uPushedBackVal; public UInputStream(InputStream in) { uIn = in; uPushedBack = false; uPushedBackVal = -1; } @Override public int read() throws IOException { if (uPushedBack) { uPushedBack = false; return uPushedBackVal; } return uPushedBackVal = uIn.read(); } public void unread() { if (uPushedBack) throw new IllegalStateException("Already pushed back a byte"); uPushedBack = true; } }
Here is how you use the UInputStream
InputStream in = new UInputStream(/*other stream object*/); int c; while ((c = in.read()) != -1) { if (c == 'A') { in.unread() doSomethingStartsWithA(in); } }
Leave a Reply