All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tecacet.jflat8.impl.CSVBasedCoreFlatFileReader Maven / Gradle / Ivy

Go to download

Convert flat files to Java Beans and vice versa. Some supported formats are CSV, fixed-width, arbitrary regex, and more. JFlat 8 is highly extensible and can be adopted to support additional formats.

There is a newer version: 0.0.5
Show newest version
package com.tecacet.jflat8.impl;

import com.tecacet.jflat8.BeanMapper;
import com.tecacet.jflat8.CSVFileFormat;
import com.tecacet.jflat8.CoreFlatFileReader;
import com.tecacet.jflat8.FlatFileReaderCallback;
import com.tecacet.jflat8.RowRecord;

import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.function.Predicate;

/*
 * Parsing implementation class
 */
class CSVBasedCoreFlatFileReader implements CoreFlatFileReader {

	private final BeanMapper beanMapper;
	private final CSVFileFormat csvFormat;

	private Predicate beanPredicate;

	public CSVBasedCoreFlatFileReader(BeanMapper beanMapper, CSVFileFormat csvFormat) {
		super();
		this.beanMapper = beanMapper;
		this.csvFormat = csvFormat;
	}

	@Override
	public void read(InputStream is, FlatFileReaderCallback callback) throws IOException {
		InputStreamReader reader = new InputStreamReader(is, "UTF-8");
		CSVParser parser = csvFormat.parse(reader);
		int line = 0;
		for (Iterator i = parser.iterator(); i.hasNext();) {
			CSVRecord csvRecord = i.next();
			line++;
			if (line <= csvFormat.getSkipLines()) {
				continue;
			}
			RowRecord rowRecord = new CSVRowRecord(csvRecord);
			T bean = beanMapper.apply(rowRecord);
			if (beanPredicate != null && !beanPredicate.test(bean)) {
				continue;
			}
			callback.accept(rowRecord, bean);
		}
		parser.close();
		reader.close();
	}

	public void setBeanPredicate(Predicate beanPredicate) {
		this.beanPredicate = beanPredicate;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy