从扫描仪到PrintWriter的字符串数据

时间:2015-07-11 02:29:47

标签: java inputstream

我正在尝试将数据从String传递到PrintWriter,同时从名为Server.java和Client.java的两个类之间的BufferedReader读取。我的问题是我无法处理从Scanner对象中读取数据的代码块抛出的异常(标记如下)。

Client.java

package root;

/**
 * @author Noah Teshima
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Socket clientSocket;

    private BufferedReader bufferedReader;
    private InputStreamReader inputStreamReader;
    private PrintWriter printWriter;

    private Scanner scanner;

    public static void main(String[] args) {
        new Client("localhost", 1025);
    }

    public Client(String hostName, int portNumber) {
        try {
            this.clientSocket = new Socket(hostName, portNumber);
            this.bufferedReader = new BufferedReader(this.inputStreamReader = new InputStreamReader(this.clientSocket.getInputStream()));
            this.printWriter = new PrintWriter(clientSocket.getOutputStream());
            String msg = "",
                    msg2 = "";

            this.printWriter.println(this.getClass());
            this.printWriter.flush();
            System.out.println(this.getClass().getName() + " is connected to " + this.bufferedReader.readLine());

            while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
                this.printWriter.println(this.getClass().getName() + ": " + msg);
                this.printWriter.flush();

                while((msg2 = this.bufferedReader.readLine()) != null) {
                    System.out.println(msg2);
                }
            }

            this.clientSocket.close();
        }catch(IOException exception) {
            exception.printStackTrace();
        }
    }
}

堆栈追踪::

Exception in thread "main" java.lang.NullPointerException
    at root.Client.<init>(Client.java:47)
    at root.Client.main(Client.java:25)

用于从BufferedReader读取并写入PrintWriter的代码对于这两个类都是相同的,所以我只发布了Client.java。如果有人想看到其他类文件,我很乐意这样做。

1 个答案:

答案 0 :(得分:1)

使用之前

while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem

您应该初始化scanner 使用它时scanner对象为null,因此为NullPointerException。

我在代码中的任何地方都没有看到scanner = new Scanner(...); 也许你已经忘记了它?