File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NPE when wrapping a Reader in a BufferedReader twice

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • 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 ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explaination. Refactoring my arguments to take the BufferedReader reference worked perfectly.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic