univocity-parsers简介
工作中经常会遇到需要导出或者解析csv的需求,Java中处理csv的开源库也有很多,本文主要介绍通过univocity-parsers
来解析和生成csv,univocity-parsers
源码存放于github,在写这篇文章的时候univocity-parsers
最新版为2.8.4
使用详解
在详解介绍之前,我们先通过一个简单的例子来看看如何使用univocity-parsers
@Slf4j
public class HowToUse {
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Student {
@Parsed(field = "userNumber")
private String userNumber;
@Parsed(field = "userName")
private String userName;
@Parsed(field = "age")
private Integer age;
}
public static final String[] HEADERS = new String[]{"userNumber", "userName", "age"};
@Test
public void howToUse() throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// 生成CSV内容
Student student = new Student("1111111111111111111111", "testUser", 20);
final CsvWriterSettings csvWriterSettings = new CsvWriterSettings();
csvWriterSettings.setHeaderWritingEnabled(Boolean.TRUE);
csvWriterSettings.setHeaders(HEADERS);
csvWriterSettings.setRowWriterProcessor(new BeanWriterProcessor<>(Student.class));
CsvWriter writer = new CsvWriter(outputStream, csvWriterSettings);
writer.processRecord(student);
writer.close();
final byte[] out = outputStream.toByteArray();
log.info("output: {}", new String(out));
// 解析CSV内容
CsvParserSettings csvParserSettings = new CsvParserSettings();
final BeanListProcessor beanListProcessor = new BeanListProcessor(Student.class);
csvParserSettings.setProcessor(beanListProcessor);
CsvParser csvParser = new CsvParser(csvParserSettings);
csvParser.parse(new ByteArrayInputStream(out));
final List<Student> students = beanListPr