Java is a library for importing CSV files into beans, and there is OpenCSV. As described in the article Java CSV library "opencsv", you can import column names and bean property names in association with each other. In this article, I will introduce the correspondence when converting the value of the file and importing it into the bean.
An example of date conversion is written on StackOverflow of here. Set the conversion class in the annotation converter
and convert.
An example of converting a string to a date is provided as an implementation sample.
Converts the created_at
column in the file to the LocalDateTime
type.
SampleCsvBean.java
public class SampleCsvBean {
@CsvBindByName(column = "id")
private Long id;
@CsvBindByName(column = "name")
private String name;
@CsvCustomBindByName(column = "created_at", converter = SampleConverter.class)
private LocalDateTime createdAt;
}
Suppose the file has a date value in the format 20140101 00:00:00
.
Format this to LocalDateTime in the converter class.
SampleConverter.java
public class SampleConverter extends AbstractBeanField {
@Override
protected Object convert(String s) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
return LocalDateTime.parse(s, dtf);
}
}
Recommended Posts