Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent of ungetc In java

Tags:

java

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.

like image 343
Pooria Avatar asked Feb 05 '10 05:02

Pooria


2 Answers

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.

like image 144
Charles Miller Avatar answered Nov 16 '22 06:11

Charles Miller


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.

like image 37
Chandra Sekar Avatar answered Nov 16 '22 06:11

Chandra Sekar