Saturday, 15 February 2014

bufferedreader - Java NullPointerException in reading -



bufferedreader - Java NullPointerException in reading -

this question has reply here:

using bufferedreader.readline() in while loop properly 3 answers

i have problem reading socket read if value isn't null doesnt't works.

@override public void run() { system.out.println("reading socket"); while(true){ seek { if(!(br.readline().equals(null)))read += br.readline(); } grab (ioexception e) { system.out.println("error " + e); } } }

here error:

exception in thread "thread-4" java.lang.nullpointerexception @ connection.createconnection.run(createconnection.java:61) @ java.lang.thread.run(unknown source)

if br.readline() returns null, calling .equals(null) on throw exception - won't homecoming true. want compare reference identity null.

calling .equals(null) never useful, unless you're testing equals implementation works :)

additionally, you'll skipping every other line calling readline() twice on each loop iteration.

you want like:

string line; if ((line = br.readline()) != null) { read += line; }

... except painfully slow due repeated string concatenation. should using stringbuilder instead.

also, doing of in loop catches ioexception seems recipe disaster - if phone call fails, it's very it'll maintain failing forever, whereupon programme hung in tight loop. should stop when exception, rather keeping going. example:

try { string line; while ((line = reader.readline()) != null) { read += line; // or builder.append(line); } } grab (ioexception e) { // whatever want }

finally, consider value of whitespace, both horizontal , vertical, benefits of using braces in single-statement if statements etc. line if(!(br.readline().equals(null)))read += br.readline(); compact @ expense of readability.

java bufferedreader

No comments:

Post a Comment