Search code examples
javastringnumberformatexception

Java String.split() - NumberFormatException


So, here's the thing, I've got this code:

public static void main(String[] args) {
    try {
        FileInputStream fstream = new FileInputStream("test.txt");
        // Use DataInputStream to read binary NOT text.
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine = br.readLine();
        String[] split = strLine.split(" ");

        System.out.println(Integer.parseInt(split[0]));
        in.close();
    }
    catch (Exception e) {//Catch exception if any
        System.err.println("Error: " + e);
    }
}

let's say I have a file named test.txt, with just "6 6". So, it reads first line and splits that line into two strings. The problem is that I can use Integer.parseInt for the split[1], but I can't use that method for split[0] (System.out.println(split[0]) prints "6"), which outputs me an error of:

Error: java.lang.NumberFormatException: For input string: "6"

UPDATE: It might be problem of eclipse, because if I compile my .java files in terminal with javac, I don't get any exceptions!:))

UPDATE2: solved. something went wrong while saving with Kate. Don't know what, but gedit works better:D Thank you all.


Solution

  • Just try with: hexdump -C test.txt if you have linux, you can see the non-printable chars you have.

    Also the trim() answer it's fine.