简体   繁体   中英

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.

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.

This problem at the start of the file is usually due to a BOM , which some software (mainly Notepad in fact) like to put at the start of Unicode files.

Open the file in a good text editor and configure it to save the files without the BOM.

If you can't change the file, skip the first char when reading it.

I'd try the following to rule out spurious/unexpected characters:

.. setup/read code in main method...
String[] split = strLine.split(" ");
for (String s : split) {
      System.out.println(String.format("[%s] => integer? %b", s, isInteger(s)));
}
... the rest of the main method....


private static boolean isInteger(String n) {
    try {
        Integer.parseInt(n);
    } catch(NumberFormatException e) {
        return false;
    }
    return true;
}

If you see anything inbetween the square brackets that isnt a number, or where the integer? returns false thats a likely the problem

如果您能够确定正在读取的文件的实际编码,则可以对其进行显式设置,以便将任何多余的字节正确地转换为字符。

new InputStreamReader(new FileInputStream(...), <encoding>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM