1 year ago
#343761
lance-java
OpenCsv: Can I specify the locale once instead of repeating it in every @CsvBindByName?
I'm using OpenCSV to parse csv files which needs to work when run in both the UK and Germany. When parsing numbers we need to specify the locale so that OpenCSV knows which decimal separator ('.' for UK, ',' for DE) and thousands separator (',' for UK, '.' for DE)
One option for doing this is specifying the locale on every @CsvBindByName instance
public class MyRowBackingBean {
@CsvBindByName(column = "Quantity", locale = "en-GB")
@CsvNumber("#0.0#")
private BigDecimal quantity;
@CsvBindByName(column = "Amount", locale = "en-GB")
@CsvNumber("#0.0#")
private BigDecimal amount;
}
I'd like to avoid repeating the locale for every field so I'd like a global way of doing this.
The code to parse the csv looks something like this:
char seperator = ';';
CSVParser parser = new CSVParserBuilder().withSeparator(separator).build();
MappingStrategy<R> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(MyRowBackingBean.class);
try (Reader reader = ...) {
CSVReader csvReader = new CSVReaderBuilder(reader).withCSVParser(csvParser).build();
CsvToBean<R> csvToBean = new CsvToBeanBuilder<R>(csvReader)
.withMappingStrategy(mappingStrategy)
.withFilter(...)
.build();
List<MyRowBackingBean> beans = csvToBean.parse()
...
}
I've looked through the following classes but can't find a setDefaultLocale(...) method or similar
java
locale
number-formatting
opencsv
0 Answers
Your Answer