I'm writing a program in java (already wrote a version in C too). I really need to put a character back to the input-stream after I read it. This can be accomplished by ungetc()
in C/C++, and I was wonder how can I do the same thing in Java?
For those of you don't know C/C++:
char myc = (char)System.in.read();
and I check the value of myc and now I want to put back myc in to the System.in
! so again when I call System.in
, I get that value. (But How can I do this?)
NOTE: I'm looking for exact technique. Please do not advise me to catch it or log it somewhere else and read off from there, because I know how to those kinda stuff. What I'm interested in is equivalent of ungetc()
in Java if there's any.
Cheers.
You are looking for PushbackInputStream
Java's IO library is designed so the primitives are really basic and additional functionality is added through composition. For example, if you wanted to buffer input from a file, you would call new BufferedInputStream(new FileInputStream("myfile.txt"));
or if you wanted to read from the stream as text using UTF-8 encoding you'd call new InputStreamReader(new FileInputStream("myfile.txt"), "UTF-8");
So what you want to do is create a PushbackInputStream with new PushbackInputStream(System.in);
The caveat here is you're not actually pushing the bytes back onto standard input. Once you've read from System.in it's gone, and no other code accessing System.in will be able to get at that byte. Anything you push back will only ever be available from particular PushbackInputStream you created to handle the data.
If the input stream supports marking you can use the mark() and reset() methods to achieve what you intend.
You can wrap System.in
into a BufferedInputStream or a BufferedReader to gain marking support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With