This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have the following code. What I would like to do is read each line from the BufferedReader directly into a StringBuffer to reduce memory overhead. Once it gets to the end of the data stream I would like it to exit the while loop.
It reads the stream fine but when I get to the end of the stream it returns null and keeps printing null without exiting the loop. Any ideas?
That isn't doing what you think it is.
What it is actually doing is reading the next line from the buffer, calling the toString method on the returned String object (which will be null when the end of file is reached and hence the NullPointerException). It then passes the String object to the StringBuffer's append method which returns a reference to itself (so you can chain appends) which you then check is not null - it will always be non null.
The big question is why do you think this is even saving memory overhead? A String object is being created by the call to readLine so why not just assign it to a String variable?
Also why are you using StringBuffer and not StringBuilder?
Joined: Jan 15, 2013
I did notice that StringBuilder is faster than StringBuffer. What would be the proper way to know that you have reached the end of the stream?
Carl Bernardi wrote:What would be the proper way to know that you have reached the end of the stream?
Joined: Aug 05, 2005
Carl Bernardi wrote:
Just out of interest what are these lines supposed to be doing ?
You appear to read a String from the stream, add it to the StringBuffer, print it and then delete it from the StringBuffer.
If all you want to do is print the contents of the stream then this will do it
Joined: Jan 15, 2013
This is what I am doing.
Joined: Aug 07, 2007
As I said earlier there is no need to put the String into a StringBuffer or StringBuilder for that matter just assign the read in string to a String variable and then call split on it.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: read from bufferedreader into stringbuffer with using string