代码之家  ›  专栏  ›  技术社区  ›  user3243499

如何将带有头的CSV文件流到Java中的HASMAPH < String,Bug >?

  •  -1
  • user3243499  · 技术社区  · 7 年前

    我有一个示例csv文件,如下所示(一个虚拟的csv文件结构供参考):

    Col0, Col1, Col2, Col3, Col4, Col5
    str1, str2, str3, str4, str5, 45.545
    str1, str2, str3, str4, str5, 45.545
    str1, str2, str3, str4, str5, 45.545
    str1, str2, str3, str4, str5, 45.545
    str1, str2, str3, str4, str5, 45.545
    

    我正在尝试将此csv文件读取到 HashMap<String, Double> 其中键生成为 (Col1 + "|" + Col2 + "|" + Col3 + "|" + Col4 + "|" + Col0) and value as Col5 .

    我在跟踪一篇类似的文章( How to convert csv to a map using Java 8 Stream )但将col5转换为double时出错,如下所示:

    java.lang.NumberFormatException:空字符串

    以下是我当前使用的代码:

        private void convertCsvtoMap(final String filePath) {
            try {
                Stream<String> lines = Files.lines(Paths.get(filePath));
                Map<String, Double> resMap = lines.skip(1).map(line -> line.split(",")).collect(
                        Collectors.toMap(line -> (line[1] +  "|" + line[2] +  "|" + line[3] + "|" + line[4] + "|" + line[0]), line -> Double.parseDouble(line[5])));
    
    
            } catch (IOException e) {
                e.getLocalizedMessage();
            }
        }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   halfer Jatin Pandey    7 年前

    我不会给你完整的解决方案,但这里有一个解决这个问题的方法,

    步骤:

    • 读取文件(我正在使用扫描仪)。
    • 使用拆分行 , 定界符。
    • 创建 钥匙 和 价值 使用拆分的值。
    • 把它加到你的地图上。

    代码片段:

    private void convertCsvtoMap(final String filePath) {
        try (Scanner in = new Scanner(new File(filePath))) {
            String line = null;
            Map<String, Double> resMap = new HashMap<>();
            while (in.hasNextLine()) {
                line = in.readLine();
                String[] fields = line.split(",");
                String key = fields[0].trim() + "|" + fields[1].trim() + ...;
                double value = Double.parseDouble(fields[5].trim());
                resMap.put(key, value);
            }
        } catch (Exception ex) {
            /* Handle Exception */
        }
    }
    

    注: 我没有编译代码,它可能有一些语法问题。

        2
  •  0
  •   Ryuzaki L    7 年前

    错误消息清楚地表明您正在尝试将空字符串解析为double,我建议使用一个util方法将值解析为double,如果发生任何异常,请将默认值设置为 0.0

    private void convertCsvtoMap(final String filePath) {
        try {
            Stream<String> lines = Files.lines(Paths.get(filePath));
            Map<String, Double> resMap = lines.skip(1).map(line -> line.split(",")).collect(
                    Collectors.toMap(line -> (line[1] +  "|" + line[2] +  "|" + line[3] + "|" + line[4] + "|" + line[0]), line -> stringToDouble(line[5])));
    
    
        } catch (IOException e) {
            e.getLocalizedMessage();
        }
    }
    
    public Double stringToDouble(String value) {
        try {
            return Double.parseDouble(value);
        }catch(NumberFormatException ex) {
            System.out.println(" Error while parsing string to double "+ex);
        }
        return 0.0;
    }