通过 PrintWriter 来自 Scanner 的字符串数据

String data from a Scanner through a PrintWriter

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

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 的代码对于两个 class 是相同的,所以我只发布了 Client.java。如果有人想看另一个 class 文件,我很乐意这样做。

使用前

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

您应该已经初始化 scanner
scanner 对象在您使用时为空,因此出现 NullPointerException。

我在你的代码中没有看到 scanner = new Scanner(...);
也许你忘记了?