从CSV文件读取时,数组索引超出范围

问题描述 投票:0回答:6

我正在尝试使用BufferedReader读取CSV文件,但由于某种原因,我在7行后得到了一个超出范围的异常。我在另一个CSV文件(30行)上尝试了这个确切的算法,它运行正常。 Here是相关的CSV文件。

    String spellPath = "file path is here";

    FileReader y = new FileReader(spellPath);
    BufferedReader x = new BufferedReader(y);
    ArrayList<Card> ArrayList = new ArrayList<Card>( );   //dynamic data type

    for( String p = x.readLine(); p != null ; p = x.readLine()){

        String [] stArray = p.split(",");
        ArrayList.add(new Card( stArray[1], stArray[2])); //new card with name and desc only

    }

    System.out.println(ArrayList.toString());

是文件的问题还是算法的问题?

java csv exception buffered reader
6个回答
2
投票

有一条线“为你在场上的每张法术卡获得500攻击力和防御力。”不包含任何,。所以stArray[]的长度为1。

其他的事情:Java数组是零基础。

for( String p = x.readLine(); p != null ; p = x.readLine()){应该是while ((String p = x.readLine())!= null ){


3
投票

你的问题是连续2次调用p = x.readLine()

for( String p = x.readLine(); p != null ; p = x.readLine()){
    ...
}

因此,读取2行,并且仅检查1行为空

您需要将循环更改为

while (true) {
    String p= x.readLine();
    if (p == null) break;

    ...
}

1
投票

试试这个。

while(x.readLine() != null){
---`enter code here`
}

1
投票
while((String p = x.readLine()) != null){

    String [] stArray = p.split(",");
    ArrayList.add(new Card( stArray[0], stArray[1])); //new card with name and desc only

}

System.out.println(ArrayList.toString());

这应该有效


1
投票

你在循环中调用x.readLine()twice。因此,您在阅读时跳过线条。

更好的方法是使用CSVReader而不是缓冲的阅读器。

CSVReader reader = new CSVReader(new FileReader(fName), ',','"','|');
    List content = reader.readAll();//do not use this if CSV file is large
    String[] row = null;

    for (Object object : content) {
        row = (String[]) object;
        row = Arrays.toString(row).split(",");
        //now you have a row array with length equal to number of columns
    }

这是获取CSVReader的链接 - CSVReader Download


0
投票

错误就在这里

String [] stArray = p.split(",");
 ArrayList.add(new Card( stArray[1], stArray[2]));

添加此条件并检查

String [] stArray = p.split(",");
ArrayList.add(new Card( stArray[0], stArray[1]));
© www.soinside.com 2019 - 2024. All rights reserved.