简体   繁体   中英

Trouble reading data from a CSV file

I'm attempting to read data from a CSV file, then put each row into an object, then place the object inside an arraylists of objects. I seem to be getting an error on this line

int age = fileReader.nextInt();

Here is my full code

/*
 * 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 testfileio;

import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
/**
 *
 * @author gregf
 */
public class TestFIleIO {

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) 
            throws FileNotFoundException {
        Company jam = new Company();

        File csv = new File("C:\\Users\\gregf\\Documents\\NetBeansProjects\\TestFIleIO\\employees.csv");
        Scanner fileReader = new Scanner(csv);

        fileReader.useDelimiter(",|\n");
        //skips first row (column headers)
        fileReader.nextLine();

        while(fileReader.hasNext()) {
            String name = fileReader.next();
            int age = fileReader.nextInt();
            fileReader.nextLine();

            try {
                jam.setEmployees(new Employee(name, age));
            }
            catch(Exception ex) {
                System.out.println(ex);
            }
        }

        System.out.println(jam);
    }

}

Error

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at testfileio.TestFIleIO.main(TestFIleIO.java:50)
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:1328: The following error occurred while executing this line:
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:948: Java returned: 1
BUILD FAILED (total time: 0 seconds)

A few notes:

Employee is an object with the name: String and age: int data fields

Company is an object that contains an ArrayList of Employee type and has a toString method to print all the employees' names and ages.

Since I have to use this in a project, so I can't use any libraries.

If you have any idea how to solve this, please share, thanks a lot.

Likely you have an input that has some unexpected characters that cannot be parsed as an integer. These may be regular printable characters, or these may be unprintable characters.

Examine your input data. Let your app report the offending data. Retrieve a string rather than an integer. Then attempt to parse using the Integer class. Add a try-catch to trap for parsing error. On error, report the length and content of the offending string.

Tip: Use a library to help with reading/writing CSV. I like Apache Commons CSV , but there are others to choose from as well.

It is likely that you are reading in some special characters, I ran into that a fair amount as well so i developed a little module and co-module to read in csv file lines right here:

static Vector<String> specialLine(String input) {
    Vector<String> returner = new Vector<String>();
    int index1=0, index2=0;
    int indexq=input.indexOf('"'), indexc=input.indexOf(',');
    boolean quote = true;
    while(indexq!=-1||indexc!=-1){
        if((indexq>indexc||indexq==-1)&&indexc!=-1) {
            index2=indexc;
            quote=false;
        }else {
            index2=indexq;
            quote=true;
        }
        if(!quote) {
            returner.add(input.substring(index1,index2));
            input = input.substring(index2+1,input.length());
            index1=0;
        }else {
            String[] temp = read_through(input);
            index1=0;
            returner.add(temp[0]);
            input = temp[1];
        }
        indexq=input.indexOf('"');
        indexc=input.indexOf(',');
        quote=false;
    }
    if(quote==false) {
        returner.add(input);
    }
    return returner;
}
static String[] read_through(String input) {
    String[] returner = new String[2];
    boolean stillIn = true;
    int steppy=0, quoteCount=0;
    while(stillIn&&steppy<input.length()) {
        steppy++;
        quoteCount=0;
        while(steppy<input.length()&&input.charAt(steppy)=='\"') {
            quoteCount++;
            steppy++;
        }
        if(quoteCount%2==1) {
            stillIn=false;
        }
    }
    if(steppy>=input.length())
        steppy=input.length()+1;
    returner[0] = String.format("\"%s\"", input.substring(1,steppy-1));
    if(steppy+1>input.length())
        steppy=input.length()-1;
    returner[1] = input.substring(steppy+1,input.length());
    return returner;
}

It mainly takes advantage of the fact hat all special characters are inside double quoted cells and all double quotes have an adjacent double quote, so the escape and entrance sequences are to find an odd number of double quotes in a row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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