我有一个名为EmpQuery的类,我正在尝试为Employee类创建一个对象数组,以保存来自employeedatabase.csv文件的数据。 数据库显示如下所示。我需要使用流处理算法..
Loop till EOF{
read in 1 record
Deal with that record completly
}
EX。
Employee ID,Full Name,Department,Start Date,Earnings
EMP001,Adele M. Fulton,Engineering,10/28/2008,"$104,000.00"
EMP002,Ali T. Herman,Engineering,2/27/2012,"$337,522.00"
EMP003,Alika C. Crawford,Engineering,6/2/2009,"$144,000.00"
到目前为止,我只是设置了这么多 公共类EmployeeDB {
private static String[] empID = new String[300];
private static String[] empName = new String[300];
private static String[] department = new String[300];
private static String[] startDate = new String[300];
private static String [] earnings = new String[300];
private static String [] empDataBase = new String[300];
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
fillDataArray();
}
public class employee{
String empID;
String empName;
String department;
String startDate;
int earnings;
public employee(String ID,String Name,String dept,String sDate,int earn){
empName = Name;
empID = ID;
department = dept;
startDate = sDate;
earnings = earn;
}
public employee( String ID, String Name) {
empName = Name;
empID = ID;
department = "";
startDate = "";
earnings = 0;
}
public employee(){
empName = "";
empID = "";
department = "";
startDate = "";
earnings = 0;
}
}
private static String[] fillDataArray() throws FileNotFoundException {
File DatabaseFile = new File("EmpDB_lab7.csv");
Scanner inputFile = new Scanner(DatabaseFile);
String InputLine;
String [] empDBTemp = null;
int i=0;
while (inputFile.hasNextLine()) {
InputLine = inputFile.nextLine();
empDBTemp = InputLine.split("-");
empID[i] = empDBTemp[1];
empName[i] = empDBTemp[2];
department[i] = empDBTemp[3];
startDate[i] = empDBTemp[4];
earnings[i] = empDBTemp[5];
}
return empDBTemp;
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at employeedb.EmployeeDB.fillDataArray(EmployeeDB.java:76)
at employeedb.EmployeeDB.main(EmployeeDB.java:28)
Java Result: 1
答案 0 :(得分:1)
CSV解析比显示的更难,因此您应该使用预先存在的库,例如Super CSV
您的CSV列名称应与您的bean字段名称匹配(或完全跳过标题),收益可能是字符串,否则您将要使用CellProcessor来解析它。
将数据读入数组和流处理是矛盾的。
ICsvBeanReader csvReader = new CsvBeanReader(new FileReader("employeedatabase.csv"), CsvPreference.STANDARD_PREFERENCE);
String[] header = csvReader.getHeader(false);
EmployeeDB employeeDB;
while((employeeDB = csvReader.read(EmployeeDB.class, header)) != null) {
System.out.println(employeeDB.getEmpName());
}
csvReader.close();
并且
public class EmployeeDB {
private String empID;
private String empName;
private String department;
private String startDate;
private String earnings;
...getters/setters...
}
我将标题更改为:
EmpID,EmpName,Department,StartDate,Earnings