【问题标题】:java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 when trying to read csv [duplicate]java.lang.ArrayIndexOutOfBoundsException:长度=1;尝试读取 csv 时 index=1 [重复]
【发布时间】:2020-01-09 06:54:37
【问题描述】:

我在尝试读取 csv 文件时遇到问题,错误显示如下:java.lang.ArrayIndexOutOfBoundsException: length=1; index=1。我试过在 StackOverflow 中搜索,错误和上面一样。

代码:

private void readCSVFile(String csvNameFile) {
    try {
        File readFolderCSV = new File(Environment.getExternalStorageDirectory() + "/Download/" + csvNameFile);
        CSVReader csvReader = new CSVReader(new FileReader(readFolderCSV.getAbsoluteFile()));
        String[] nextLine;
        while((nextLine = csvReader.readNext()) != null) {
            Log.e("TAG", nextLine[0] + nextLine[1] + nextLine[2] + nextLine[3] + nextLine[4]);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(MasterUoM.this, "The specified file was not found", Toast.LENGTH_SHORT).show();
    }
}

我的CSV文件:

【问题讨论】:

  • 这意味着您在该数组中只有一项(在索引 0 处),但您正在尝试访问第二项(索引 1)。因此,nextLine[1] 很可能会导致 Exception,因为其中只有一个 String(可能是整行?)。
  • 根据您的屏幕截图,您的 nextLine[] 数组中似乎只有 2 个对象。所以 nextLine[2] 或以上应该按预期给出一个 ArrayIndexOutOfBoundException 。
  • 您的csv 每行仅包含 2 列,但您尝试获取 3、4、5 导致异常
  • @Md.Asaduzzaman MyCSVFile 只是一个例子。当我在类别名称列中有很多类别名称数据时怎么样?

标签: java android opencsv


【解决方案1】:

你的问题在这里:

while((nextLine = csvReader.readNext()) != null) {
            Log.e("TAG", nextLine[0] + nextLine[1] + nextLine[2] + nextLine[3] + nextLine[4]);
        }

您在没有长度安全的情况下进行日志记录。您有一行 nextLine[1] 不存在。那是因为 csvreader 不返回单元格而是返回行。

您需要使用 split 方法拆分行。 Java split string to array 再次检查表格的长度是否足够。

3,4 和 5 单元访问会给您带来同样的麻烦。

【讨论】:

    【解决方案2】:

    您似乎正在尝试获取 column[2] 和 column[3] & column[4] 但 csv 没有 5 列,

     Log.e("TAG", nextLine[0] + nextLine[1] + nextLine[2] + nextLine[3] + nextLine[4]);
    

    您可以通过打印 nextLine.length() 来检查它。

    【讨论】:

    • 感谢您的回答。我检查了 nextLine.length,结果为 1。然后我尝试更改 nextLine[0],结果成功。非常感谢!
    猜你喜欢
    • 2018-06-02
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2018-11-05
    • 2015-05-22
    • 2014-05-13
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多