CSV读取器拾取空白行

时间:2015-09-28 13:33:00

标签: java csv

我有一个程序可以读入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]);

2 个答案:

答案 0 :(得分: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);
    

答案 1 :(得分:1)

通常情况下,使用一些好的图书馆是最好的方法,如果你这样做不是为了教育。 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();