Univocity-parsers解析csv文件

断鸿 2019年07月15日 129次浏览

[toc]

Univocity-parsers是针对CSV/TSV/定宽文本文件解析的开源项目,优点是功能齐全,api简洁。

        <dependency>
            <groupId>com.univocity</groupId>
            <artifactId>univocity-parsers</artifactId>
            <version>2.8.1</version>
        </dependency>
    public List<T> parse(Path path) {
        CsvParserSettings csvParserSettings = new CsvParserSettings();
        Integer numOfRowsToSkip = getNumOfRowsToSkip();
        //设置跳过注释行
        csvParserSettings.setNumberOfRowsToSkip(numOfRowsToSkip == null ? 0 : numOfRowsToSkip);
        csvParserSettings.setLineSeparatorDetectionEnabled(true);
        csvParserSettings.setHeaderExtractionEnabled(true);
        Class<T> aClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        BeanListProcessor<T> beanListProcessor = new BeanListProcessor<>(aClass);
        csvParserSettings.setProcessor(beanListProcessor);
        CsvParser csvParser = new CsvParser(csvParserSettings);
        Charset charset = getCharset();
        //指定编码
        csvParser.parse(path.toFile(), charset == null ? Charset.forName("UTF-8") : charset);
        List<T> list = beanListProcessor.getBeans();
        parseAfter(list);
        return list;
    }