Search code examples
javastringsocketsparseint

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


I'm trying to build a client-server application. The client reads the IP and port which it connects to from files within the jar file. The port is read as a string from the "port.ovrlrd" file, which contains nothing else but the port number (I checked for spaces etc). However, when I try to convert the string to an int it gives me a NumberFormatException, but I don't know why. Here is the code:

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); 

Solution

  • You read and assign values to line2 until it's null. (The termination conditional is that line2 is null.)

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

    If you were to print line2 immediately after this loop, you'll see that it's null. So when you get to:

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

    line2 is null, which cannot be parsed as an integer.