Alan
Alan

Reputation: 589

Integer.Parse throws NumberFormatException on excel fetched String

in my program I fetch each line of an Excel table. When I split the line, in order to parse each String of the array to an Integer, the Exception mentioned in the title gets thrown. The table is populated in this way:

0;1;100;4;1000;8;8
...

The table is saved as .csvthat's why I split by ;

Idea: File values contain false chars:
I already checked for 0-width characters...

Code snippet:

try {
        bufferedReader = new BufferedReader(new FileReader(fileName));

        while ((line = bufferedReader.readLine()) != null) {
            if(flag == 0){
                tableSize = line.split(";").length;
                System.out.println("TableSize is: "+tableSize);
                flag = 1;
                table1 = new int[tableSize][tableSize];
            }
            String [] tempStrings = line.split(";");
            int [] tempInts = new int[tableSize];

            for(int i=0; i<tableSize;i++){
                tempInts[i] = Integer.parseInt(tempStrings[i]);
                System.out.println(tempInts[i]);
            }

            table1[row] = tempInts;
            row++;
        }

Any help is highly appreciated!
Edit: After creating a new .csv file same problem Stacktrace of the NumberFormatException:

java.lang.NumberFormatException: For input string: "0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at excercise.Main.fillTableByCsv(Main.java:53)
at excercise.Main.main(Main.java:22)

Upvotes: 0

Views: 140

Answers (1)

Boann
Boann

Reputation: 50031

Your CSV file begins with a byte order mark encoded in UTF-8. You can see it, for example, if you open the file in a hex editor:

Although the extra bytes EF BB BF are not visible, they are what's upsetting Integer.parseInt.

See Byte order mark screws up file reading in Java for some solutions.

Upvotes: 1

Related Questions