【问题标题】:CSV reader picking up blank linesCSV 阅读器读取空行
【发布时间】:2015-09-28 13:32:59
【问题描述】:

我有一个程序读取CSV 文件并将第一行和最后一行存储为JSONObject。我当前的实现是跳过最后一行并读入 null 值作为数据对象。

创建/保存 CSV 文件以消除任何空白或空值的正确方法是什么?

CSV

   TIME_STAMP,TOTAL,APPLES,ORANGES,PEARS,GRAPES,TANGERINES,PINEAPPLES,CARROTS,UNKNOWN 
    7/1/2015 4:00,19474,1736,275,8366,5352,3003,393,349,

代码

String firstLine = "";
String lastLine = "";

int count = 0;
if(reader != null){
    String aux = "";
    String lastLineMinusOne = "";
    while ((aux = reader.readLine()) != null) {
        if(count == 0)firstLine = aux;
            lastLineMinusOne = lastLine;
            lastLine = aux;
            count ++;
        }
        logger.info("Count = " + count);             
        String[] columns = firstLine.split(",");
        String[] data = lastLine.split(",");
        logger.info(firstLine);
        logger.info(lastLine);

日志

    2015-09-28 13:41:42,370 [ajp-0.0.0.0-8009-2] INFO  com.ChartData - Count = 3
    2015-09-28 13:23:27,745 [ajp-0.0.0.0-8009-3] INFO  com.ChartData - TIME_STAMP,TOTAL,APPLES,ORANGES,PEARS,GRAPES,TANGERINES,PINEAPPLES,CARROTS,UNKNOWN
    2015-09-28 13:23:27,745 [ajp-0.0.0.0-8009-3] INFO  com.ChartData -

错误

java.lang.ArrayIndexOutOfBoundsException: 10
    at com.ChartData.getCSV(ChartData.java:75)

第 75 行 -> jObject.put("val", data[i]);

【问题讨论】:

    标签: java csv


    【解决方案1】:

    你可以:

    1. 读为described here时解析行:

      while ((aux = reader.readLine()) != null) {
          String auxTrimmed = aux.replaceAll("(?m)^[ \t]*\r?\n", "");
          // more code
      }
      
    2. 如果您总是遇到这个问题,请忽略最后一行:

      String[] data = lastLineMinusOne.split(",");
      logger.info(lastLineMinusOne);
      

    【讨论】:

      【解决方案2】:

      通常,使用一些好的库是最好的方法,如果你这样做不是为了教育。 CSV 看起来很简单,直到您面对引号中的文本、转义字符、不同的行尾等。

      在您的情况下,您可以使用 apache commons.csv

         <dependency>
              <groupId>org.apache.commons</groupId>
              <artifactId>commons-csv</artifactId>
              <version>1.0</version>
         </dependency>
      

      以及简短的用法示例,请注意 withIgnoreEmptyLines(true)

      final CSVFormat format = CSVFormat.DEFAULT
                      .withIgnoreEmptyLines(true)
                      .withDelimiter(',');
      CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"), format);
      Iterator<CSVRecord> iterator = parser.iterator();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-09
        • 2018-02-01
        • 2016-12-15
        • 1970-01-01
        • 2017-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多