如果我们在java bean中有一个bean(即一个对象)而不是一个原始类型,那么我们如何使用OpenCSV映射内部bean的属性
例如flightId of flight 豆子 SCHEDULE(scheduleId,航班,航线和其他领域)
飞行(飞行,其他领域)
路线(路由ID,otherfields)
package temp.csv;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import com.model.Schedule;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import au.com.bytecode.opencsv.bean.CsvToBean;
public class Abcd {
public static void main(String[] args) {
// TODO Auto-generated method stub
CsvToBean<Schedule> csv = new CsvToBean<Schedule>();
String csvFilename = "D:\\Travel_Portal\\Schedule\\SCHEDULE_4-10_12.26.54.csv ";
ColumnPositionMappingStrategy<Schedule> strat = new ColumnPositionMappingStrategy<Schedule>();
strat.setType(Schedule.class);
String[] columns = new String[] { "scheduleId", "flight.flightId",
"route.routeId", "availSourceDest", "availSourceVia",
"availViaDest", "fareSourceDest", "fareSourceVia",
"fareViaDest" };
// the fields to bind do in your JavaBean
strat.setColumnMapping(columns);
CSVReader csvReader = null;
try {
csvReader = new CSVReader(new FileReader(csvFilename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<Schedule> list = csv.parse(strat, csvReader);
try {
for (Object object : list) {
Schedule schedule = (Schedule) object;
System.out.println(schedule.getScheduleId() + " "
+ schedule.getFlight() + schedule.getRoute());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
//这是CSV文件
"SID121","AI101","RID101",100,-1,-1,5000,-1,-1,"2013-10-20 11:30:00","0000-00-00 00:00:00","0000-00-00 00:00:00","2013-10-20 12:00:00","DID105"
// Schedule Class
public class Schedule implements java.io.Serializable {
private String scheduleId;
private Flight flight;
private Deal deal;
private Route route;
private int availSourceDest;
private Integer availSourceVia;
private Integer availViaDest;
private double fareSourceDest;
private double fareSourceVia;
private double fareViaDest;
private Date sourceTime;
private Date viaArrTime;
private Date viaDeptTime;
private Date destTime;
//getter and setter
}
//Flight
public class Flight implements java.io.Serializable {
private String flightId;
private Provider provider;
private int capacity;
//getter setter
}