missInTrouble
missInTrouble

Reputation: 21

NullPointerException and BufferedReader

my program keeps throwing nullPointerException at me and I have no idea why. I thought maybe it's because of the bufferedReader but I'm not sure.

String line = reader.readLine();
while (!line.isEmpty()) {
    line = repairLine(line);
    tree.add(line);
    line = reader.readLine();
}

Yes, it is wrapped in try - catch block. It says that the problem is on the while-line. It didn't work with "if (line != null)". I really don't know what could cause that. Thanks you for any help.

Upvotes: 1

Views: 4973

Answers (2)

WIlson
WIlson

Reputation: 1

I have had this same error and it meant that the socket is closing on the other connected client while it is trying to read on the server.

To add some context, I am running a server and various clients are connecting to it via java sockets. I was having this error on the server side when the client closes the socket.

So to solve the issue I decided to close both server side and client side sockets after every connection. The way I have done this is before client is closed it sends a "quit" message to the server before closing its sockets. When the server reads the "quit" message it will also close its sockets.

For example:

  • Client side
if(Quit){
   if(mySocket != null && !mySocket.isClosed()) {
        output.println("quit");
        output.flush();
        
        try {
            mySocket.close();
        } catch (IOException e) {
            System.out.println("Close net variables exception - " + e.getMessage());
        }
    }
}
  • Server side
String line = input.readLine(); //Thread stops here untill it reads something

if(line.equals("something")){
   do_something();
else if(line.equals("quit")){
   try {
        mySocket.close();
    } catch (IOException e) {
        System.out.println("Close net variables exception - " + e.getMessage());
    }
else{
   do_default();
}

Worked for me, hope it helps!

Upvotes: 0

Chetan Kinger
Chetan Kinger

Reputation: 15212

The problem seems to be with the following lines of your code :

String line = reader.readLine();
while (!line.isEmpty()) {   

}

If there is nothing to read from the file, line will be null. Thus the exception in the while loop. You are trying to call a method on a null reference.

That being said, the traditional way of reading lines from a file is to assign the line read to a variable in the while condition itself (code not tested) :

String line = "";
while ((line=reader.readLine()!=null) && !line.isEmpty()) {
    line = repairLine(line);
    tree.add(line);
}

Upvotes: 4

Related Questions