【问题标题】:Get CSV file header using apache commons使用 apache commons 获取 CSV 文件头
【发布时间】:2016-07-16 03:04:42
【问题描述】:

过去 2 小时我一直在寻找解决问题的方法,但徒劳无功。我正在尝试使用 Apache commons 读取 CSV 文件,我能够读取整个文件,但我的问题是如何仅提取数组中 CSV 的标头?

【问题讨论】:

    标签: java csv apache-commons-csv


    【解决方案1】:

    在 Kotlin 中:

    val reader = File(path).bufferedReader()
    val records = CSVFormat.DEFAULT.withFirstRecordAsHeader()
        .withIgnoreHeaderCase()
        .withTrim()
        .parse(reader)
    
    println(records.headerNames)
    

    【讨论】:

      【解决方案2】:

      我到处寻找,甚至上面的解决方案也不起作用。 对于遇到此问题的其他任何人,都可以这样做。

      Iterable<CSVRecord> records;
      Reader in = new FileReader(fileLocation);
      records = CSVFormat.EXCEL.withHeader().withSkipHeaderRecord(false).parse(in);
      Set<String> headers = records.iterator().next().toMap().keySet();
      

      请注意,您对 .next() 的使用已经消耗了 CSV 的一行。

      【讨论】:

        【解决方案3】:
        BufferedReader br = new BufferedReader(new FileReader(filename));
        
        CSVParser parser = CSVParser.parse(br, CSVFormat.EXCEL.withFirstRecordAsHeader());
        
        List<String> headers = parser.getHeaderNames();
        

        这对我有用。最后一行是您需要的,将解析器找到的标头提取到字符串列表中。

        【讨论】:

        【解决方案4】:

        默认情况下,CSVParser 读取的第一条记录将始终是标题记录,例如在下面的例子中:

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
        FileReader fileReader = new FileReader("file");
        CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
        List csvRecords = csvFileParser.getRecords();
        

        csvRecords.get(0) 将返回头记录。

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多