File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes NPE when wrapping a Reader in a BufferedReader twice Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "NPE when wrapping a Reader in a BufferedReader twice" Watch "NPE when wrapping a Reader in a BufferedReader twice" New topic
Author

NPE when wrapping a Reader in a BufferedReader twice

Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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
 
subject: NPE when wrapping a Reader in a BufferedReader twice