[英]reading a .csv file into an array in java
我有一個名為 EmpQuery 的類,我試圖為我的 Employee 類創建一個對象數組,以保存來自employeedatabase.csv 文件的數據。 數據庫如下所示。 我需要使用流處理算法..
Loop till EOF{
read in 1 record
Deal with that record completly
}
前任。
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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.