我想将这个csvFile读取到Flight类对象的数组中,其中每个索引将引用包含来自csvFile的记录的对象。
这是飞行类的蓝图。它不完整,所以我只提供数据成员。
public class Flight {
private String flightID;
private String source;
private String destination;
private <some clas to handle time > dep;
private <some clas to handle time> arr;
private String[] daysOfWeek;
private <some clas to handle date> efff;
private <some clas to handle date> efft;
private <some clas to handle dates> exc;
}
我想实现这样一个函数:
public class DataManager {
public List<Flight> readSpiceJet() {
return new ArrayList<Flight>();
}
}
请随意修改,并请帮助我。:)
你可以试试OpenCSV Framework
看一下这个例子:
import java.io.FileReader;
import java.util.List;
import com.opencsv.CSVReader;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvToBean;
public class ParseCSVtoJavaBean
{
public static void main(String args[])
{
CSVReader csvReader = null;
try
{
/**
* Reading the CSV File
* Delimiter is comma
* Default Quote character is double quote
* Start reading from line 1
*/
csvReader = new CSVReader(new FileReader("Employee.csv"),',','"',1);
//mapping of columns with their positions
ColumnPositionMappingStrategy mappingStrategy =
new ColumnPositionMappingStrategy();
//Set mappingStrategy type to Employee Type
mappingStrategy.setType(Employee.class);
//Fields in Employee Bean
String[] columns = new String[]{"empId","firstName","lastName","salary"};
//Setting the colums for mappingStrategy
mappingStrategy.setColumnMapping(columns);
//create instance for CsvToBean class
CsvToBean ctb = new CsvToBean();
//parsing csvReader(Employee.csv) with mappingStrategy
List empList = ctb.parse(mappingStrategy,csvReader);
//Print the Employee Details
for(Employee emp : empList)
{
System.out.println(emp.getEmpId()+" "+emp.getFirstName()+" "
+emp.getLastName()+" "+emp.getSalary());
}
}
catch(Exception ee)
{
ee.printStackTrace();
}
finally
{
try
{
//closing the reader
csvReader.close();
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
}
}
编辑1:解析日期:
String dateString;
Date date;
public void setDateString(String dateString) {
// This method can parse the dateString and set date object as well
}
public void setDate(Date date) {
//parse here
}