0

Is it possible to configure Univocity CSV parser to skip some rows based on predefined conditions like for example values in the cells?

For example I have the following CSV file:

name,city
Alex,NY
Mike,London
Dan,Sydney

and I'd like to skip from the processing(and remove from resultset) all rows where city equal London.

I'm unable to find such functionality in documentation. Please advise.

alexanoid
  • 24,051
  • 54
  • 210
  • 410

2 Answers2

1

Not sure if it's the best solution, however give a look:

    StringReader input = new StringReader(""
        + "name,city\n"
        + "Alex,NY\n"
        + "Mike,London\n"
        + "Dan,Sydney\n");

    CsvParserSettings settings = new CsvParserSettings();

    settings.setAutoConfigurationEnabled(true);
    settings.setHeaderExtractionEnabled(true);

    settings.getFormat().setLineSeparator("\n");
    settings.selectFields("name", "city");

    settings.setProcessor(new RowListProcessor() {

        @Override
        public void rowProcessed(String[] row, ParsingContext context) {
            super.rowProcessed(row, context);
            if (row[1].equalsIgnoreCase("London")) {
                context.skipLines(1);
            }
        }
    });

    CsvParser parser = new CsvParser(settings);

    parser.beginParsing(input);

    Object[] row;
    while ((row = parser.parseNext()) != null) {
        System.out.println(Arrays.toString(row));
    }

    parser.stopParsing();
0

You can use Iterator approach when going throught file and just skip rows you don't need. See iterating approach for more details. Or even iterating using beans.

art
  • 174
  • 1
  • 9