无法从CSV文件读取数据

时间:2019-07-23 06:56:52

标签: java csv

我正在尝试从CSV文件中读取数据,然后将每一行放入一个对象,然后将该对象放入对象的数组列表中。我似乎在这条线上出现错误

int age = fileReader.nextInt();

这是我的完整代码

/*
 * 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);
    }

}

错误

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)

一些注意事项:

Employee是一个名称为:String and age:int数据字段的对象

Company是一个对象,其中包含Employee类型的ArrayList并具有toString方法来打印所有员工的姓名和年龄。

由于我必须在项目中使用它,所以我不能使用任何库。

如果您有解决方法的任何想法,请分享,非常感谢。

2 个答案:

答案 0 :(得分:1)

可能您的输入中包含一些无法解析为整数的意外字符。这些可能是常规的可打印字符,也可能是不可打印的字符。

检查您的输入数据。让您的应用报告违规数据。检索字符串而不是整数。然后尝试使用Integer类进行解析。添加一个try-catch来捕获陷阱以分析错误。错误时,报告错误字符串的长度和内容。

提示:使用库可帮助读取/写入CSV。我喜欢 Apache Commons CSV ,但还有其他选择。

答案 1 :(得分:0)

您可能正在阅读一些特殊字符,我也碰到了那么多字,所以我开发了一个小模块和协模块以在此处读取csv文件行:

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;
}

主要利用以下事实:所有特殊字符都位于双引号内,并且所有双引号都具有相邻的双引号,因此转义和进入序列要在一行中找到奇数个双引号。