【发布时间】: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