【问题标题】:Java: NumberFormatException when trying to read a port from a fileJava:尝试从文件中读取端口时出现 NumberFormatException
【发布时间】:2019-09-02 19:51:53
【问题描述】:

我正在尝试构建一个客户端-服务器应用程序。客户端从 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); 

【问题讨论】:

  • 异常告诉你原因。它的消息包含无法解析的字符串。显然它不是一个数字。在这种情况下,它为空,因为您读取到文件的末尾,您使用while ((line2 = reader2.readLine()) != null) 对其进行了测试。所以在这个循环之后显然line2 必须为空。没有其他可能。您不需要循环,只需一个 readLine() 调用。

标签: java string sockets parseint


【解决方案1】:

您读取 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,无法解析为整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多