Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Null pointer exception reading from text file.  RSS feed

 
Prem Bhazee
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I am trying to read values from a text file.And my text file is as follows

0,4
dsddss,2332
dddfdfdf,23233


But I am getting null pointer exception in the while loop.



Can you please help.

Thanks
Bhazee
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This line of code

while ((strValue = objBufferedReader.readLine()) != null && (strValue = objBufferedReader.readLine())!= "") {

reads two lines of text from the file. It compares the first one to null, then reads another and compares it to the literal "". Imagine that the program is about to read the last line of the file. The first "readLine" above reads it, and it's not null, so that test succeeds; then you read another line, and it's null, but you compare that to "", and that test also succeeds, so you go into the body of the loop. The call to strValue.trim() then throws an exception.

There are quite a few changes you should make here. First of all, you want to call readLine() only once; any other tests should use that variable strValue directly, without reading another line!

Also, you cannot use "==" or "!=" to compare the contents of String objects, as you are doing here; these operators check to see if two objects are the same object, rather than whether they contain the same characters. Always use the "equals()" method to compare strings.

Thirdly, the "trim()" means you thing that there might be stray whitespace on a line; if that's the case, then comparing the untrimmed strValue to "" might fail, even though the line is blank -- it might just have spaces on it. In that case, you'd want to trim it before comparing it to whitespace.

Make sense?
 
Prem Bhazee
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest.

That makes lot of sense.

Thanks for the quick reply.

Bhazee
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!