Search code examples
javacsvexceptionnumberformatexceptioncsvreader

Why is an exception thrown on parsing data from the first string array but not when skipping the first array?


In my system I have an Excel reader that also reads csv files.

This is the way I read the csv file:

        Path path = Paths.get(this.getFilePath());
        CSVParser parser = new CSVParserBuilder().withSeparator(';').build();

        try(BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8);
            CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser).build()) {

            rows = reader.readAll();

This works. The data from the csv file is stored in a list of string arrays.

Now I noticed something when reading the data from the list which I don't understand.

This is the way I read the data from the list:

if (rows != null && rows.size() > 1) {
            for (String[] row : rows) {
                                    
                int i = Integer.parseInt(row[0]);
                String name = row[1];
                double d = Double.parseDouble(row[2].replace(",", "."));

            }
        }

If the first array is fetched from the list and the first string from the array is parsed from String to int, java.lang.NumberFormatException: For input string: " 27" is thrown.

But if the first array (first excel line) is skipped:

            if (rows != null && rows.size() > 1) {
            for (int i = 1; i < rows.size(); i++) {  //i = 1, skipp first array(excel line)
                String[] row = rows.get(i);

                int i = Integer.parseInt(row[0]);
                String name = row[1];
                double d = Double.parseDouble(row[2].replace(",", "."));

            }
        }

This way no java.lang.NumberFormatException: For input string: is thrown.

I do not understand why a java.lang.NumberFormatException is thrown if the first array (excel line) is not skipped.

The first line from the excel file is needed and should not be skipped. Can it have something to do with reading the excel file? With the reader I use?

Does anyone know this problem or can anyone help me?


Solution

  • You get these error, because your number has a leading blank. You can use trim before parsing the number. These should remove the blank(s) and the parse error.

            if (rows != null && rows.size() > 1) {
            for (int i = 1; i < rows.size(); i++) {  //i = 1, skipp first array(excel line)
                String[] row = rows.get(i);
    
                int i = Integer.parseInt(row[0].trim());
                String name = row[1];
                double d = Double.parseDouble(row[2].replace(",", "."));
    
            }
        }
    

    You can also try:

    Integer.parseInt(row[0].replaceAll("\\D+", ""));
    

    This removes allnon Digits from the String.