简体   繁体   English

从CSV文件读取时出现NumberFormatException错误

[英]A NumberFormatException error when reading from CSV file

I have the following csv file: 我有以下csv文件:

No_Reduction    No_Reduction    No_Reduction    No_Reduction
1               15              1               9
0               7               0               0
3               1               5               1

I would like to read the file and calculate the sum for each line. 我想读取文件并计算每一行的总和。 The first line is some technique that I'm using in my project (forget about the duplication). 第一行是我在项目中使用的某种技术(忘记重复)。 To do so, I did the following: 为此,我做了以下工作:

BufferedReader readerBuffer = new BufferedReader(new FileReader("location"));
BufferedWriter bw = new BufferedWriter(new FileWriter("location",true));
while ((line = readerBuffer.readLine()) != null) {
    if(line.contains("Reduction")) {
        bw.write(convertCSVtoArrayList(line).get(0)); //I want to write the technique name in the new file
        bw.write("\n");
    }else if(!line.contains("NA")) {
        ArrayList<String> data_per_class = convertCSVtoArrayList(line);                 
        List<Double> doubleList = data_per_class.stream().map(Double::valueOf).collect(Collectors.toList()); //this is line 46
        double sum = this.calculateSum(doubleList);
        bw.write(sum);
        bw.write("\n");
    }
}
bw.close();

The convertCSVtoArrayList method: convertCSVtoArrayList方法:

public static ArrayList<String> convertCSVtoArrayList(String pathCSV) {
    ArrayList<String> result = new ArrayList<String>();

    if (pathCSV != null) {
        String[] splitData = pathCSV.split("\\s*,\\s*");
        for (int i = 0; i < splitData.length; i++) {
            if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
                result.add(splitData[i].trim());
            }
        }
    }

    return result;
}

Basically, the error is: 基本上,错误是:

Exception in thread "main" java.lang.NumberFormatException: For input string: "" 1""
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.lang.Double.valueOf(Double.java:502)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at MockerClass.applyForCase(MockerClass.java:46)
    at MockerClass.main(MockerClass.java:16)

Note that if I remove the first line (the one that contains No_Reduction ), the error disappears !! 请注意,如果我删除第一行(包含No_Reduction ),该错误将消失!

How can I solve this issue? 我该如何解决这个问题?

Let's give a non-answer: such things are to be expected when you re-invent the wheel. 让我们给出一个没有答案的东西:当您重新发明轮子时,会发生这种事情。

Meaning: CSV parsing is harder than you think. 含义:CSV解析比您想象的要难。 Typically your own hand-written parser works for the input data that you could think up. 通常,您自己的手写解析器会处理可能想到的输入数据。 The second you throw valid CSV data at it from a different source, something that is slightly more complicated, your parser will break. 第二秒钟,您从其他来源向其抛出有效的CSV数据,这稍微有些复杂,解析器将中断。

So: that exception tells you that this string " 1" can't be parsed as number, and as the other answers explain, that is due to wrong "parsing" of other elements. 因此:该异常告诉您,字符串" 1"无法解析为数字,正如其他答案所解释的,这是由于其他元素的错误“解析”所致。

Thus, my recommendation: in case you want to have a real CSV parser, use an existing library for that, like openCSV or apache commons CSV . 因此,我的建议是:如果您想拥有一个真正的CSV解析器,请为此使用一个现有的库,例如openCSVapache commons CSV

It appears that it's trying to convert your "No Reduction" line into integers, and failing. 似乎正在尝试将“不减少”行转换为整数,但失败了。 Is the code getting into your if(line.contains("Reducation")) block? 代码是否进入了if(line.contains(“ Reducation”))块?

Perhaps add this just as a test 也许将此添加为测试

if(line.contains("Reduction") || line.trim().isEmpty()) 

Perhaps your input file has a newline at the end? 也许您的输入文件末尾有换行符?

Seems your convertCSVtoArrayList is incorrect. 似乎您的convertCSVtoArrayList不正确。 The split parameter and condition for null and length are incorrect. split参数和null和length条件不正确。 I suppose to change that method to: 我想将该方法更改为:

    public static ArrayList<String> convertCSVtoArrayList(String pathCSV) {
    ArrayList<String> result = new ArrayList<>();
    if (pathCSV != null) {
        String[] splitData = pathCSV.split("\\s+");
        for (int i = 0; i < splitData.length; i++) {
            if (splitData[i].length() != 0) {
                result.add(splitData[i].trim());
            }
        }
    }
    return result;
}

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

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