Interface CsvToBeanFilter


  • public interface CsvToBeanFilter
    Filters allow lines of input to be ignored before a bean is created.

    Using a filter means you are looking at the data from the input after it has been parsed, but before a bean has been created and populated.

    Filters must be thread-safe.

    Where possible use the BeanVerifier as you have the ability to to check specific fields in the object. If you know the order of the data OR your checks are checking something other than the content/structure/format of the data (IE filter out any line that does not have 10 columns) then use the CsvToBeanFilter.

    Here's an example showing how to use CsvToBean that removes empty lines. Since the parser returns an array with a single empty string for a blank line that is what it is checking.

     
     private class EmptyLineFilter implements CsvToBeanFilter {
    
     	private final MappingStrategy strategy;
    
     	public EmptyLineFilter(MappingStrategy strategy) {
     		this.strategy = strategy;
        }
    
     	public boolean allowLine(String[] line) {
     		boolean blankLine = line.length == 1 && line[0].isEmpty();
     		return !blankLine;
        }
    
     }
    
     public List<Feature> parseCsv(InputStreamReader streamReader) {
     	HeaderColumnNameTranslateMappingStrategy<Feature> strategy = new HeaderColumnNameTranslateMappingStrategy();
     	Map<String, String> columnMap = new HashMap();
     	columnMap.put("FEATURE_NAME", "name");
     	columnMap.put("STATE", "state");
     	strategy.setColumnMapping(columnMap);
     	strategy.setType(Feature.class);
     	CSVReader reader = new CSVReader(streamReader);
     	CsvToBeanFilter filter = new EmptyLineFilter(strategy);
     	return new CsvToBean().parse(strategy, reader, filter);
     }
     
     
    See Also:
    BeanVerifier
    • Method Detail

      • allowLine

        boolean allowLine​(java.lang.String[] line)
        Determines if a line from the CSV file will be included in the output of CsvToBean.
        Parameters:
        line - A line of data from the CSV file
        Returns:
        True if the line is to be included in the output. Otherwise, false.