2

Why is it a good thing to push back bytes into the stream? When I process the stream,I can ignore the byte or I can modify it,if I want to do that on this way:

    try(InputStream is = new FileInputStream("test.txt")){

        int aByte;
        char c;

        while((aByte = is.read()) != -1){

            c = (char)aByte;

            if(c == 'h') {
               c = 'X';
            }

            System.out.print(c);
        }

I checked the javadocs,but I still don't understand and why should I put back data into the stream in certain cases.Sorry guys.

jani777
  • 53
  • 4

1 Answers1

1

push back has to do with the option to peek ahead and test is some condition is true or false. If false you would like to go on as if you did not peak ahead so you have to push back the stream as manny characters as you peeked ahead. else you can replace the peak ahead part and continue from there.

[See] http://tutorials.jenkov.com/java-io/pushbackinputstream.html

[Or] http://www.java-samples.com/showtutorial.php?tutorialid=390

[Or] book: "The Complete Reference Part 2 by Herbert Schildt".

The PushbackInputStream is intendended to be used when you parse data from an InputStream. Sometimes you need to read ahead a few bytes to see what is coming, before you can determine how to interprete the current byte. The PushbackInputStream allows you to do that. Well, actually it allows you to push back the read bytes into the stream. These bytes will then be read again the next time you call read(). --Jenkov--

int c; 
while ((c = f.read()) != -1) { 
  switch(c) { 
  case '=': 
  if ((c = f.read()) == '=') {
    System.out.print(".eq."); 
  } else { 
    System.out.print("<-"); 
  f.unread(c); 
  } 
}

In this way you stay in the flow of reading.

Caution: PushbackInputStream has the side effect of invalidating the mark( ) or reset( ) methods of the InputStream used to create it. Use markSupported( ) to check any stream on which you are going to use mark( )/reset( ). --www.java-samples.com--

irJvV
  • 892
  • 8
  • 26