how opencsv BeanToCsv resolve line break will split java beans

36 Views Asked by At

ArrayList list = new ArrayList<>();

    CustomerAttribute attr1 = new CustomerAttribute().setAttributeId(123).setAttributeValue("abc,\nbcd");
    CustomerAttribute attr2 = new CustomerAttribute().setAttributeId(123).setAttributeValue("abc");
    list.add(attr1);
    list.add(attr2);
    HeaderColumnNameMappingStrategy<CustomerAttribute> strategy = new HeaderColumnNameMappingStrategy<>();
    strategy.setType(CustomerAttribute.class);
    Writer writer = new FileWriter("sample.csv", StandardCharsets.UTF_8);
    StatefulBeanToCsv<CustomerAttribute> build = new StatefulBeanToCsvBuilder<CustomerAttribute>(writer)
            .withMappingStrategy(strategy)
            .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
            .build();

I just set two java beans to convert csv file, but due to the value "abc,\nbcd", the csv file is enter image description here

I just except two lines because it will cause parse this csv file to java bean error. how can i resolve this line break in bean field. I don't know witch filed will contains line break, so I can't do check and replace line break.

1

There are 1 best solutions below

1
Roger Xing On
public String getAttributeValue() {
    return attributeValue.replaceAll("\n", " ");
}

The temporary solution I can think of is to perform replaceAll on the get method of the line break field that may appear