Univocity Parsers Library

Very good parsing library.
Official Website
Univocity Parsers – Maven Repository

public class ExampleCsvToPojoParser {
  
    private final Logger logger = LoggerFactory.getLogger(CsvToPojoParser.class);
  
    public <T> List<T> parseFileToPojo(Class<T> clazz, String fileName) {
  
        BeanListProcessor<T> rowProcessor = new BeanListProcessor<T>(clazz);
  
        CsvParserSettings parserSettings = new CsvParserSettings();
  
        parserSettings.setRowProcessor(rowProcessor);
        parserSettings.setHeaderExtractionEnabled(true);
        parserSettings.setLineSeparatorDetectionEnabled(true);
        parserSettings.setSkipEmptyLines(true);
  
        CsvParser parser = new CsvParser(parserSettings);
        try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
            parser.parse(resourceAsStream);
        } catch (IOException e) {
            logger.error("Cannot read file " + fileName, e );
        }
        return rowProcessor.getBeans();
    }
}

Then you can put there class like this (which will match the file):

public class Users {
  
    @Trim
    @NullString(nulls = { " ", "" })
    @Parsed(field = "USER_ID")
    private Long userId;
    @Trim
    @NullString(nulls = { " ", "" })
    @Parsed(field = "USER_NAME")
    private String userName;
    //getters & setters
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s