我正在尝试读取一个csv文件,并将其String值转换为double。
public void trq() throws IOException, ParseException {
Test4 obj = new Test4();
String path = "transposedData1.csv";
BufferedReader readerBuffer = new BufferedReader(new FileReader(path));
String line;
List<Double> results = new ArrayList<Double>();
while ((line = readerBuffer.readLine()) != null) {
if(!line.contains("NA")) {
ArrayList<String> data_per_class = convertCSVtoArrayList11(line);
List<Double> doubleList = data_per_class.stream()
.map(Double::parseDouble)
.collect(Collectors.toList()); // the error here
// do other things
}
}
}
public static ArrayList<String> convertCSVtoArrayList11(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;
}
CSV文件看起来像:
1.0 8.0 4.0 6.0
3.0 2.0 1.0 5.0
7.0 1.0 8.0 1.0
1.0 2.0 1.0 4.0
请注意,没有标题。该文件以无标题的值开头。我收到的错误是:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""1.0""
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.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:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
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:566)
at Test4.trq(Test4.java:1063) \\ I mentioned that in the code above
您知道如何解决此问题吗?
替换
pathCSV.split("\\s*,\\s*");
with
pathCSV.split("\\s+");
这样数字就可以在空格上分开。目前,它们正以额外的"
存储到结果中,例如""1.0""
应该存储为"1.0"
。
根据您看到的错误消息,该号码实际上被一对引号引起来,这很可能导致呼叫失败。
一种快速解决方案是使用asString = substring(1, asString.length() - 2);
,其中asString
是要解析为双精度型的字符串。
返回前使用result.add(splitData[i].trim(). replaceAll("/"","") )