开发者

equivalent of ungetc In java

开发者 https://www.devze.com 2022-12-19 00:47 出处:网络
I\'m writing a program in java (already wrote a version in C to开发者_JAVA百科o). 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

I'm writing a program in java (already wrote a version in C to开发者_JAVA百科o). 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.


A RandomAccessFile can .seek( .getFilePointer() - 1 ).

0

精彩评论

暂无评论...
验证码 换一张
取 消