Can you recommend a Java library for reading, parsing, validating and mapping rows in a comma separated value (CSV) file to Java value objects (JavaBeans)?
views:
5346answers:
7We have used http://opencsv.sourceforge.net/ with good success
I also came across another question with good links: http://stackoverflow.com/questions/123/csv-file-to-xml
I've had good success both parsing and writing CSV files from Java with OpenCVS. If you want to read or write Excel compatible spreadsheet with Java, the POI library from Apache is the way to go.
The CSV File to XML question asked previously seems to answer all my questions.
OpenCSV (http://opencsv.sourceforge.net/) also does binding to JavaBeans using a Column Position Mapping Strategy
ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(YourOrderBean.class);
String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean
strat.setColumnMapping(columns);
CsvToBean csv = new CsvToBean();
List list = csv.parse(strat, yourReader);
JSEFA (http://jsefa.sourceforge.net) also seems to do everything I need - particularly binding to Java objects - in addition to supporting FLR and XML
Hey, I have an open-source project for that: JFileHelpers. I think the main advantage is that it uses Java Annotations, take a look:
If you have this bean:
@FixedLengthRecord()
public class Customer {
@FieldFixedLength(4)
public Integer custId;
@FieldAlign(alignMode=AlignMode.Right)
@FieldFixedLength(20)
public String name;
@FieldFixedLength(3)
public Integer rating;
@FieldTrim(trimMode=TrimMode.Right)
@FieldFixedLength(10)
@FieldConverter(converter = ConverterKind.Date,
format = "dd-MM-yyyy")
public Date addedDate;
@FieldFixedLength(3)
@FieldOptional
public String stockSimbol;
}
And wants to parse this file:
....|....1....|....2....|....3....|....4
1 Antonio Pereira 10012-12-1978ABC
2 Felipe Coury 201-01-2007
3 Anderson Polga 4212-11-2007DEF
All you have to do is this:
FileHelperEngine<Customer> engine =
new FileHelperEngine<Customer>(Customer.class);
List<Customer> customers =
new ArrayList<Customer>();
customers = engine.readResource(
"/samples/customers-fixed.txt");
Also, it supports master-detail, date and format conversion, and a lot more. Let me know what you think!
Best regards!