在Java中读取csv

时间:2013-04-17 04:05:39

标签: java csv

我有一个csv,我试图读入一个对象数组。我一直收到以下错误...... java.util.InputMismatchException 我认为这是因为它读取的文件由空格而不是逗号分隔。我相信我需要使用String.split()方法,但我不确定如何做到这一点。有什么建议。这是我到目前为止的代码......

public class Prog7
{
public static void main(String[] args)
{
    Part[] parts;
    int numParts;
    int partNumber;
    String description;
    double price;
    int quantity;
    String city;

    parts = new Part[100];
    numParts = 0;

    Scanner inFile = null;

    /*
     * open file
     */
    try
    {
        inFile = new Scanner( new File( "C:/COSC        210/Assignment#7/parts.txt" ) );
    }
    catch ( FileNotFoundException e )
    {
        System.err.println( "Error: file not found" );
    }

    /*
     * read file using each record to create a State object
     * and add that State object to the PopulationData object
     */
    while( inFile.hasNext() )
    {
        partNumber = inFile.nextInt();
        description = inFile.next();
        price = inFile.nextDouble();
        city = inFile.next();
        quantity = inFile.nextInt();


        Part p = new Part(partNumber, description, price, 
                          quantity, city);
        parts[numParts]= p;
        numParts++;

        for (int i = 0; i < numParts; i++)
        {
            System.out.println(parts[i].getPartNumber());
        }
    }
}
}

以下是我正在使用的文本文件:

12345,Left-Handed Bacon Stretcher,125.95,PGH,2

24680,Smoke Shifter,0.98,PGH,48

86420, Pre-dug Post Hole,2.49,ATL,34

25632,Acme Widget,98.29,LOU,342

97531,Anti-Gravity Turbine,895.29,ATL,3

24680,Battery-Powered Battery Charger,252.98,ATL,2

12345,Left-Handed Bacon Stretcher,125.95,LOU,35

97531,Anti-Gravity Turbine,895.29,PHL,8

00000,Glass Hammer,105.90,PGH,8

86420, Pre-dug Post Hole, 2.49,ATL,34

01020,Inflatable Dartboard,32.95,PGH,453

86420, Pre-dug Post Hole, 2.49,LOU,68

86420, Pre-dug Post Hole, 2.49,PGH,124

24680, Battery-Powered Battery Charger, 252.98, PHL, 5

2 个答案:

答案 0 :(得分:3)

使用scanner.useDelimiter(",");

    Scanner inFile = new Scanner(new File
                          ("C:/COSC        210/Assignment#7/parts.txt" ));
    inFile.useDelimiter(",");
    while (inFile.hasNext()) {
        int partNumber = Integer.parseInt(inFile.next());
        String description = inFile.next();
        double price = Double.parseDouble(inFile.next());
        String city = inFile.next();
        int quantity = Integer.parseInt(inFile.nextLine().replaceAll(",", ""));
        if(inFile.hasNextLine()) inFile.nextLine();
        System.out.println(partNumber+","
                +description+","
                +price+","
                +city+","
                +quantity);
    }
    inFile.close();

答案 1 :(得分:0)

默认情况下,扫描程序使用空格作为分隔符。在阅读文件之前使用scanner.useDelimiter(",")

由于内容本身可以","

,因此仍然不是万无一失

如果它用于学习那么它就没问题,否则你可以使用一些已经这样做的库,例如http://sourceforge.net/projects/opencsv/files/opencsv/

而不是固定100长度数组使用列表,就好像记录超过100个,您的代码会因异常而中断。