-
Notifications
You must be signed in to change notification settings - Fork 1
Home
A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. The structure of CSV file content is table which each line is a data record and it has one or more columns, which is very similar to a table in relational database. In java, there is the Hibernate framework for mapping an object-oriented domain model to a relational database. So why don't we have a framework which can map an object-oriented domain model to a CSV file.
In jcsvorm, it uses @CsvColumn with parameter name to handle the mapping between a field in java and a column in CSV file, like
In Java
@CsvColumn(name = "first name")
private String firstName;In CSV
| first name |
|---|
| Jack |
| Mary |
| ... |
If your CSV file doesn't have the header line, you can also use the column index to map, like
@CsvColumn(pos = 0)
private String firstName;If a column is date format in CSV, you can use format parameter to parse or write a column, like
In Java
@CsvColumn(pos = "DOB", format="yyyy-MM-dd")
private Date dob;In CSV
| DOB |
|---|
| 1978-02-17 |
| 1984-11-26 |
| ... |
After using @CsvColumn with different parameters, it will make much easier for reading and writing a CSV, just one line function call per each functionality, like:
Read
List<Student> studentList = CsvFactory.readCsv(Student.class, "data/data_with_header.csv", HeaderOption.WITH_HEADER);Write
CsvFactory.writeCsv(studentList, "data/output.csv", HeaderOption.WITH_HEADER);