Java: 尝试从文件读取端口时出现 NumberFormatException

Java: NumberFormatException when trying to read a port from a file

我正在尝试构建客户端-服务器应用程序。客户端从 jar 文件中的文件中读取它连接的 IP 和端口。端口作为字符串从 "port.ovrlrd" 文件中读取,其中只包含端口号(我检查了空格等)。但是,当我尝试将字符串转换为 int 时,它会给我一个 NumberFormatException,但我不知道为什么。这是代码:

InputStream input2 = RemoteConn.class.getResourceAsStream("/port.ovrlrd"); //Reading the port
        InputStreamReader inputReader2 = new InputStreamReader(input2);
        BufferedReader reader2 = new BufferedReader(inputReader2);
        String line2 = null;
        while ((line2 = reader2.readLine()) != null) {
            System.out.println(line2); //This prints the correct port number
        }
        reader2.close();

        while(true) {
            Thread.sleep(20000);

        try { 
              String host = line1; 
              int port =  Integer.parseInt(line2); //This is the problem line

              Socket meinEchoSocket = new Socket(host,port); 

您读取 line2 并为其赋值,直到 null。 (终止条件是 line2null。)

String line2 = null;
while ((line2 = reader2.readLine()) != null) {
  System.out.println(line2); //This prints the correct port number
}

如果您要在此循环后立即打印 line2,您会看到它是 null。所以当你到达:

int port =  Integer.parseInt(line2); //This is the problem line

line2为null,无法解析为整数