简体   繁体   English

为什么从第一个字符串数组解析数据时会抛出异常,而在跳过第一个数组时不会抛出异常?

[英]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.在我的系统中,我有一个 Excel 读取器,它也读取 csv 个文件。

This is the way I read the csv file:这是我读取 csv 文件的方式:

        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.来自 csv 文件的数据存储在字符串 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.如果从列表中获取第一个数组并将数组中的第一个字符串从 String 解析为 int,则抛出java.lang.NumberFormatException: For input string: " 27"

But if the first array (first excel line) is skipped:但是如果跳过第一个数组(第一个 excel 行):

            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.这样就不会抛出 java.lang.NumberFormatException: For input string: 。

I do not understand why a java.lang.NumberFormatException is thrown if the first array (excel line) is not skipped.我不明白如果没有跳过第一个数组(excel 行),为什么会抛出 java.lang.NumberFormatException。

The first line from the excel file is needed and should not be skipped. excel 文件的第一行是必需的,不应跳过。 Can it have something to do with reading the excel file?跟读取excel文件有关系吗? With the reader I use?配合我用的阅读器?

Does anyone know this problem or can anyone help me?有谁知道这个问题或者谁能帮助我?

You get these error, because your number has a leading blank.你得到这些错误,因为你的号码有一个前导空白。 You can use trim before parsing the number.您可以在解析数字之前使用trim 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.这从字符串中删除所有非数字。

The string it's trying to parse has a leading space: " 27".它试图解析的字符串有一个前导空格:“27”。 That is what's causing the error.这就是导致错误的原因。 The following code also throws the exception:下面的代码也会抛出异常:

public class MyClass {
    public static void main(String args[]) {
      int i = Integer.parseInt(" 27");
      System.out.println(i);
    }
}

As a general rule you should sanitize your input before parsing it.作为一般规则,您应该在解析输入之前对其进行清理。 For example, if it's going to be a numeric value, trim() the string before feeding it to parseInt() .例如,如果它是一个数字值,则在将它提供给parseInt()之前trim()该字符串。

Your parsing is not adequate.您的解析不充分。 The error you get shows that one cell contains a number with a leading space.您得到的错误表明一个单元格包含一个带前导空格的数字。

java.lang.NumberFormatException: For input string: " 27" java.lang.NumberFormatException:对于输入字符串:“27”

You call Integer.parseInt() on this cell value.您对此单元格值调用 Integer.parseInt()。 By its documentation, parseInt() rejects leading spaces.根据其文档, parseInt() 拒绝前导空格。

You will need to trim the value before calling parseInt.您需要在调用 parseInt 之前修剪该值。 See String.trim().请参见 String.trim()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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