• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

NPE when wrapping a Reader in a BufferedReader twice

 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the following code, when i pass the Reader to the method a second time, the program fails with a NullPointerException.


Output:The NPE occurs because br.readLine() returns null the second time the readAndPrint() method is called. In the actual code I'm parsing an input file that has two parts. I want to pass the Reader to one class to parse the first part, and then to another class to parse the second part. But it looks like this may not be possible. I couldn't find anything in the BufferedReader documentation that described this behavior though.
[ October 01, 2006: Message edited by: Garrett Rowe ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A BufferedReader, by definition, reads more than it returns. It reads X amount of input all at once, then doles it out over time; that's what "buffering" means.

So here, X is some number greater than the length of your entire input. The first BufferedReader you create empties the whole StringReader out; the second one has nothing left to read.

You're right that the Javadoc for BufferedReader doesn't mention this, and it probably should. The rule is, really, that once you wrap a BufferedReader around a Reader, you can't read from that raw Reader ever again, because you don't know how much data the BufferedReader has read and not handed out yet.

You really have only one choice to write the kind of code you describe: refactor so that your topmost routine creates the BufferedReader, and everything else takes one as an argument. If the whole file is line-oriented, then this makes perfect sense.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the explaination. Refactoring my arguments to take the BufferedReader reference worked perfectly.
 
reply
    Bookmark Topic Watch Topic
  • New Topic