Java客户端中的NullPointer异常?

时间:2012-10-16 20:29:08

标签: java eclipse sockets exception nullpointerexception

我正在编写一个简单的客户端,但我总是得到一个NullPointerException

            while ((input = in.readLine()) != null) {

这是我的代码:

public class ClientTest {

public static String server = "127.0.0.1";
public static int sport = 11111;
public static int cport = 11111;
private static String clientname="";
public static ExecutorService pool = Executors.newCachedThreadPool();
public static BufferedReader in = null;
public static PrintWriter out = null;
public static Socket socket = null;

public ClientTest(){
    this.clientname="";
}


public static void main(String[] args) {

    try {
        socket = new Socket(server, sport);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch(IOException e) {
        System.out.println("could not create connection:\n" + e);
        try {
            if(socket != null) socket.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    pool.execute(new Communicator());

}

public static class Communicator implements Runnable {
    @Override
    public void run() {
        String input = "";
        try {
            while ((input = in.readLine()) != null) {//here  i get the NPException
                StringTokenizer tokenizer = new StringTokenizer(input);
                tokenizer.nextToken();

                if(input.startsWith("!open")) {
                    if(tokenizer.hasMoreTokens()) System.out.print(tokenizer.nextToken() + "> ");
                    else System.out.print("> ");
                } 
                else if(input.startsWith("!exit")) {
                    System.out.print("Hallo hallo");
                } 
            }
        } catch(IOException e) {
            System.out.println("An error as occurred while reading from server - \n" + e);
        }
    }

}


}

为什么我得到NullPointerException?我还在初始化String输入。

2 个答案:

答案 0 :(得分:7)

  

我的问题是,为什么我会得到NP Exception,我还在初始化String输入!

如果NullPointerException为空,那么你会得到in ......当然可以。毕竟,如果main的第一部分中的任何内容引发异常,您就会抓住它,将其打印出来......然后继续前进!因此,如果socket.getOutputStream()引发异常,则inout都将为空。

道德:抓住一个例外并继续就好像什么都没发生一样很少一个好主意。

答案 1 :(得分:0)

我认为try块中的某些内容失败并且in未初始化,然后在运行Comunicator的异常后,in仍为空。