Example usage for org.apache.commons.csv CSVFormat RFC4180

List of usage examples for org.apache.commons.csv CSVFormat RFC4180

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVFormat RFC4180.

Prototype

CSVFormat RFC4180

To view the source code for org.apache.commons.csv CSVFormat RFC4180.

Click Source Link

Document

Comma separated format as defined by <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.

Usage

From source file:formats.db.fileformats.csv.RunnerCsv.java

public static void main(String[] args) throws IOException {

    CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',');

    //initialize the CSVParser object

    CSVParser parser = new CSVParser(new FileReader("D:\\customers.csv"), format);

    List<Customers> customersList = new ArrayList<Customers>();
    for (CSVRecord record : parser) {
        Customers customers = new Customers();

        customers.setId_cs(Integer.parseInt(record.get("id_cs")));
        customers.setF_name(record.get("f_name"));
        customers.setL_name(record.get("l_name"));
        customers.setDiscount(Integer.parseInt(record.get("discount")));
        customers.setLicense(record.get("license"));

        customersList.add(customers);/*from ww w  .ja  v  a  2 s.  co m*/
    }
    //close the parser
    parser.close();

    System.out.println(customersList);
}

From source file:com.lithium.flow.util.CsvFormats.java

@Nonnull
public static CSVFormat fromConfig(@Nonnull Config config) {
    checkNotNull(config);//from   w w  w. j  a v  a2  s. c o m
    switch (config.getString("csv.format", "default")) {
    case "default":
        return CSVFormat.DEFAULT;
    case "excel":
        return CSVFormat.EXCEL;
    case "mysql":
        return CSVFormat.MYSQL;
    case "rfc4180":
        return CSVFormat.RFC4180;
    case "tdf":
        return CSVFormat.TDF;
    case "custom":
        return CSVFormat.newFormat(getChar(config, "csv.delimiter", ','))
                .withAllowMissingColumnNames(getBoolean(config, "csv.allowMissingColumnNames"))
                .withCommentMarker(getChar(config, "csv.commentMarker"))
                .withEscape(getChar(config, "csv.escape")).withHeader(getHeader(config, "csv.header"))
                .withIgnoreEmptyLines(getBoolean(config, "csv.ignoreEmptyLines"))
                .withIgnoreSurroundingSpaces(getBoolean(config, "csv.ignoreSurroundingSpaces"))
                .withNullString(getString(config, "csv.nullString")).withQuote(getChar(config, "csv.quote"))
                .withQuoteMode(getQuoteMode(config, "csv.quoteMode"))
                .withRecordSeparator(getString(config, "csv.recordSeparator"))
                .withSkipHeaderRecord(getBoolean(config, "csv.skipHeaderRecord"));
    default:
        return CSVFormat.DEFAULT;
    }
}

From source file:com.github.horrorho.liquiddonkey.cloud.CSVWriter.java

public static CSVWriter create() {
    return new CSVWriter(CSVFormat.RFC4180);
}

From source file:gradingfun.GradeParser.java

public GradeParser(File file) {
    try {// www .ja va  2s . co m
        this.parser = CSVParser.parse(file, Charset.defaultCharset(), CSVFormat.RFC4180);
    } catch (IOException ex) {
        Logger.getLogger(GradeParser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.univocity.articles.csvcomparison.parser.CommonsCsvParser.java

@Override
public void processRows(File input) throws Exception {
    CSVFormat format = CSVFormat.RFC4180;
    CSVParser parser = CSVParser.parse(input, getEncoding(), format);
    for (CSVRecord record : parser) {
        process(record);/*from   w w  w . j  a  va2s  .  com*/
    }
}

From source file:it.incipict.tool.profiles.util.ProfilesToolUtils.java

public static List<Survey> parseSurvey(File file) throws ProfilesToolException {
    List<Survey> surveys = new ArrayList<Survey>();

    Iterable<CSVRecord> records;
    try {/*from w ww.j av  a2s  .  c  o  m*/
        Reader in = new FileReader(file.getCanonicalPath());
        records = CSVFormat.RFC4180.parse(in);
    } catch (IOException e) {
        throw new ProfilesToolException("error while reading files.", e);
    }

    // loop all surveys in CSV line by line
    // note: a single CSV can contain more surveys
    for (CSVRecord record : records) {
        int line = (int) record.getRecordNumber();
        // skip the first line because it simply contains the headers
        if (line > 1) {
            Survey survey = new Survey();
            List<String> answers = new ArrayList<String>();
            List<String> textualAnswers = new ArrayList<String>();
            // in the Survey model we can define a "RECORD OFFSET" by which
            // the parser must start
            for (int i = survey.RECORD_OFFSET; i < record.size(); i++) {
                String r = record.get(i);

                // if the "r" is empty the user has not responded
                // skip to the next answers
                if (r.isEmpty()) {
                    continue;
                }
                // if "r" isn't a numerical value and it is different than
                // ZERO_STRING (Ref. Survey model)
                // Note: the ZERO_STRING is defined in Survey Class. Its
                // value is Zero.
                if ((!r.matches("\\d*") && r.compareTo(survey.ZERO_STRING) != 0)) {
                    // Otherwise the answer is added to a list of Strings.
                    // this list will appended in queue. (*)
                    String[] str = r.split(";");
                    for (String s : str) {
                        textualAnswers.add("\"" + s + "\"");
                    }
                }
                // if "r" is a numeric value, simply add it in the answers
                // list.
                if (r.compareTo(survey.ZERO_STRING) == 0) {
                    answers.add("0");
                }
                if (r.matches("\\d*")) {
                    answers.add(r);
                }
            }
            // add the textual answers in queue (*)
            answers.addAll(textualAnswers);

            String fname = file.getName();
            survey.setProfile(fname.substring(0, fname.lastIndexOf('.')));
            survey.setAnswers(answers);
            surveys.add(survey);
        }
    }
    return (surveys != null) ? surveys : null;
}

From source file:com.univocity.articles.csvcomparison.parser.CommonsCsvParser.java

@Override
public List<String[]> parseRows(File input) throws Exception {
    CSVFormat format = CSVFormat.RFC4180;
    CSVParser parser = CSVParser.parse(input, getEncoding(), format);

    List<String[]> rows = new ArrayList<String[]>();

    for (CSVRecord record : parser) {
        String[] row = new String[record.size()];
        for (int i = 0; i < row.length; i++) {
            row[i] = record.get(i);/*ww w  .j a  v  a  2s  . c o  m*/
        }
        rows.add(row);
    }
    return rows;
}

From source file:com.danidemi.templategeneratormavenplugin.generation.impl.CsvRowSource.java

@Override
public Iterator<IRowModel> iterator() {

    try {/*from  ww  w .  j a va  2s  .c  o m*/
        // get the reader from the resource
        CSVParser parser = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);

        // get the headers
        List<String> headersAsList = new ArrayList<>(parser.getHeaderMap().keySet());

        return new TransformIteratorAdapter<CSVRecord, IRowModel>(parser.iterator(),
                r -> new CsvRowModel(r, headersAsList));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:example.csv.PostalReader.java

@Override
public void open(Serializable checkpoint) throws Exception {
    ZipFile zipFile = new ZipFile(ZIP_PATH.toFile());
    ZipEntry csvEntry = zipFile.getEntry("42NAGASA.CSV");
    InputStreamReader reader = new InputStreamReader(zipFile.getInputStream(csvEntry),
            Charset.forName("Windows-31J"));
    parser = CSVFormat.RFC4180.withHeader(HEADER).parse(reader);
    csvIter = parser.iterator();//from   w  w w .j av  a2s . c  o m
}

From source file:com.ksa.myanmarlottery.service.parser.CSVFileParser.java

public List<Result> getResult(InputStream in) throws FileNotFoundException, IOException, ParseException {
    Iterable<CSVRecord> records = CSVFormat.RFC4180
            .parse(new BufferedReader(new InputStreamReader(in, "UTF-8")));
    int i = 0;//from www.  ja  va 2s .  co m
    List<Result> resultList = new ArrayList<>();
    List<Prize> prizes = null;
    for (CSVRecord record : records) {
        if (OLD_LOTTERY_TYPE.equals(record.get(0))) { // for lottery type result
            Result result = new Result();
            result.setType(ConstantUtil.OLD_LOTTERY_TYPE);
            result.setNumberOfTimes(Integer.valueOf(record.get(1)));
            result.setResultFor(new SimpleDateFormat("dd/MM/yyyy").parse(record.get(2)));
            result.setDataProvider(record.get(3));
            result.setCompanyName(record.get(4));
            prizes = new ArrayList<Prize>();
            result.setPrizes(prizes);
            resultList.add(result);

        } else if (NEW_LOTTERY_TYPE.equals(record.get(0))) {
            Result result = new Result();
            result.setType(ConstantUtil.NEW_LOTTERY_TYPE);
            result.setNumberOfTimes(Integer.valueOf(record.get(1)));
            result.setResultFor(new SimpleDateFormat("dd/MM/yyyy").parse(record.get(2)));
            result.setDataProvider(record.get(3));
            result.setCompanyName(record.get(4));

            prizes = new ArrayList<Prize>();
            result.setPrizes(prizes);
            resultList.add(result);

        } else {
            // check validation for character.
            String character = record.get(0);
            String value = charMap.get(character);
            if (value == null) {
                throw new ParseException("Character is Not valid at Row " + i + " column:" + 0, 400);
            }
            prizes.add(new Prize(record.get(0), Integer.parseInt(record.get(1)), record.get(2), record.get(4)));
        }
        i++;
    }
    log.info("Total rows after parsing. " + i);
    return resultList;
}