Search code examples
javaintbufferedreaderfilereaderparseint

Integer.parseInt failing 'For input string: "5000"'


I'll admit it, I'm stumped. It's not a double. It's not outside of the range of an integer. It's not NAN. It's not a non-integer in any way shape or form as far as I can tell.

Why would I get that error?

Here's the code that causes it:

String filename = "confA.txt";

//Make a new filereader to read in confA
FileReader fileReader = new FileReader(filename);

//Wrap into a bufferedReader for sanity's sake
BufferedReader bufferedReader = new BufferedReader(fileReader);

//Get the port number that B is listening to
int portNum = Integer.parseInt(bufferedReader.readLine());

It fails on that last line, stating:

java.lang.NumberFormatException: For input string: "5000"

Which is the number I want.

I've also attempted

Integer portNum = Integer.parseInt(bufferedReader.readLine());

But that didn't work either. Neither did valueOf().


Solution

  • Most probably there is some unprintable character somewhere in your file line. Please consider the following example (this was tested in Java 9 jshell)

    jshell> String value = "5000\u0007";
    value ==> "5000\007"
    
    jshell> Integer.parseInt(value);
    |  java.lang.NumberFormatException thrown: For input string: "5000"
    |        at NumberFormatException.forInputString (NumberFormatException.java:65)
    |        at Integer.parseInt (Integer.java:652)
    |        at Integer.parseInt (Integer.java:770)
    |        at (#15:1)
    

    Here the string contains the "bell" character at the end. It makes parse to fail while it is not printed in exception text. I think you have something similar. The simpliest way to verify this is to check

    String line = bufferedReader.readLine();
    System.out.println("line length: " + line.length());
    

    The value other than 4 will support my idea.