简体   繁体   English

读取CSV文件,数组索引越界错误

[英]reading in CSV file, arrayindex out of bounds error

I'm attempting to read in a csv file, I've created a test file with 9 entries and their value, but my code won't read past the second line , it says the file isn't found past the second key, I've tried tweeking it as much as possible, can someone help me?我正在尝试读取一个 csv 文件,我创建了一个包含 9 个条目及其值的测试文件,但是我的代码不会读到第二行,它说在第二个键之后找不到该文件,我已经尽可能多地尝试了它,有人可以帮助我吗? sample input would include something like this but in a csv file (so each in a new line, I'm new here and still learning to edit text here): Diego,2 Maria,2 Armando,5 Ken, 1示例输入将包括这样的内容,但在一个 csv 文件中(所以每个都在一个新行中,我是新来的,并且仍在学习在这里编辑文本):Diego,2 Maria,2 Armando,5 Ken, 1

public static void main(String[] args) {

    HashMap<String, Integer> h = new HashMap<String, Integer>(511);


    try
    {
        Scanner readIn = new Scanner (new File ("test1.csv") );
        System.out.println("I'm here 1");


        while ( readIn.hasNext() )
        {               

            System.out.print(readIn.next());// for testing purposes only
            System.out.println("Check 2"); // for testing purposes only 


            String line = readIn.nextLine();
            String str[] = line.split(",");

            for (int i = 0; i < str.length ; i++)
            {
                String k = str[0];
                int v = Integer.parseInt(str[1]);
                h.insert(k , v);
            }

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

        }
        readIn.close();     
    }

    catch (ArrayIndexOutOfBoundsException ob)
    {
        System.out.println(" - The file wasn't found." );
    } 

    catch (FileNotFoundException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

A call to next() or nextLine() should be preceeded with the call to hasNext().But in you code you have checked if hasNext() returns true in the while loop,and then invoked both next() and nextLine() inside the loop.对 next() 或 nextLine() 的调用应该先于对 hasNext() 的调用。但是在您的代码中,您已经检查了 hasNext() 在 while 循环中是否返回 true,然后同时调用 next() 和 nextLine()循环内。 You can modify your code as below:您可以修改您的代码如下:

while ( readIn.hasNext() )
            {               

                String line = readIn.nextLine();
                String str[] = line.split(",");

                for (int i = 0; i < str.length ; i++)
                {
                    String k = str[0];
                    int v = Integer.parseInt(str[1]);
                    h.put(k , v);
                }

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

            }

Your for loop isn't actually serving a purpose.您的 for 循环实际上并没有达到目的。 You will notice that you never actually reference i in the loop.你会注意到你从来没有在循环中真正引用过i Prior to the OP's answer I believe you were trying to split on a string that didn't have a comma, but your code assumes that one will be there and hence the out of bounds exception.在 OP 的回答之前,我相信您试图拆分一个没有逗号的字符串,但是您的代码假定一个字符串会在那里,因此会出现越界异常。 This relates to why I was telling you that the println() was problematic.这与我告诉你println()有问题的原因有关。

As far as your question about hasNext() , this is the only way you will know that you can read another line from the file.至于您关于hasNext() ,这是您知道可以从文件中读取另一行的唯一方法。 If you try to read past the end you will run into problems.如果你试图读到最后,你会遇到问题。

Rather writing code to read CSV file on your own.而是编写代码来自己读取CSV文件。 I'd suggest you to use standard libraries like Apache Commons CSV .我建议您使用标准库,如Apache Commons CSV It provides more methods to deal with CSV , Tab separated file , etc...它提供了更多处理CSVTab separated file等的方法...

import java.io.FileReader;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

public class SO35859431 {
    public static void main(String[] args) {
        String filePath = "D:\\user.csv";
        try {
            List<CSVRecord> listRecords = CSVFormat.DEFAULT.parse(new FileReader(filePath)).getRecords();
            for (CSVRecord csvRecord : listRecords) {
                /* Get record using index/position */
                System.out.println(csvRecord.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

First there is no such insert() method in HashMap class.The correct one is put(k, v) & in while loop it should be hasNext().首先,HashMap 类中没有这样的 insert() 方法。正确的方法是 put(k, v) & 在 while 循环中它应该是 hasNext()。 Follow is my code alternate the BufferedReader.以下是我的替代 BufferedReader 的代码。

/* * To change this license header, choose License Headers in Project Properties. /* * 要更改此许可证标题,请在项目属性中选择许可证标题。 * To change this template file, choose Tools | * 要更改此模板文件,请选择工具 | Templates * and open the template in the editor.模板 * 并在编辑器中打开模板。 */ package read; */ 包读取;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Scanner;

/**
 *
 * @author Isuru Rangana Jr
 */
public class Read {

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws FileNotFoundException, IOException {
        HashMap<String, Integer> h = new HashMap<String, Integer>();

        try {
            BufferedReader readIn = new BufferedReader(new FileReader(new File("test.csv")));

            while (readIn.ready()) {

                String line = readIn.readLine();
                String str[] = line.split(",");


                for (int i = 0; i < str.length; i++) {
                    String k = str[0];
                    int v = Integer.parseInt(str[1]);
                    h.put(k, v);
                }

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

            }
            readIn.close();
        } catch (ArrayIndexOutOfBoundsException ob) {
            System.out.println(" - The file wasn't found.");
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM