• Post Reply Bookmark Topic Watch Topic
  • New Topic

PushbackInputStream

 
raddikrishna kittur
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi ,
Can you please explain the practicle usage of PushbackInputStream
Thanks in advance
KK
 
sai challa
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pushback is used on an input stream to allow a byte to be read and then returned(that is "pushed back") to the stream.The PushbackInputStream implements this idea.It provides a mechanism to "peek " at what is coming from an input stream without disrupting it.
I will illustrate their usage with a small example:
The pushback input classes are useful for finding fields within non-delimited output.Suppose that a stream consists of various non-numeric data ,followed by a number.Now suppose the stream is somewhere in the non-numeric data,and it is necessary to skip to the numericfield.Because the input is not delimited(there is no seperation character between the non-numeric data and the numeric field) we could write some code like the following:
//inreader is an InputStream which has been initialised.
int intchar;
while((intchar=inreader.read())!=-1)
{
if(Character.isDigit((char)intchar))
break;
}
This code fails because,by the time the loop is exited ,the first character of the numeric field has been read and the input stream is positioned at the second character .The code must undo the reading of the first numeric character.Reading is undone by chaining a pushback input stream onto inreader.
The code can be re-written as:
int intchar;
PushbackInputStream pbis=new PushbackInputStream(inreader);
while((intchar=pbis.read())!=-1)
{
if(Character.isDigit((char)intchar))
{
pbis.unread(intchar);
break;
}
}
The ability to push a single byte back into the data source permits the easy parsing of structured,non-delimited input.
I found this material in Java 2 Developer's handbook by Philip Heller and Simon Roberts.
Hope this helps
 
srinivasrao marri
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
some times you'll need to keep track of the intermediate streams when chaining them together. when reading an input, some times it requires to know the next byte whether to read or not. this can be done using PushbackInputStram.
PushbackInputStream pis=new PushbackInputStream(new BufferedInputStream("dept.dat")));
//speculatively you can read the next byte
int x=pis.read();
//throw it back if it is not you wanted
if(x=='*')
pis.unread(x);
reading and unreading are the only methods that apply to the pushbackinputstream
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!