gpt4 book ai didi

java - CSV 阅读器拾取空行

转载 作者:行者123 更新时间:2023-12-02 04:20:30 26 4
gpt4 key购买 nike

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

最佳答案

你可以:

  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);

关于java - CSV 阅读器拾取空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32824375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com