Example usage for org.apache.commons.csv CSVPrinter printRecord

List of usage examples for org.apache.commons.csv CSVPrinter printRecord

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVPrinter printRecord.

Prototype

public void printRecord(final Object... values) throws IOException 

Source Link

Document

Prints the given values a single record of delimiter separated values followed by the record separator.

Usage

From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java

/**
 * Write test csv file./*from ww w.  j  a va  2 s . c o  m*/
 *
 * @param mlInputs
 *            the ml inputs
 * @param append
 *            the append
 * @throws IOException
 */
public static void writeTestCsvFile(List<String> mlInputs, boolean append) throws IOException {

    if (mlInputs.isEmpty())
        return;

    // Create new students objects
    List<UserInputTrainingRecord> trainings = new ArrayList<UserInputTrainingRecord>();
    for (int index = 0; index < mlInputs.size(); index++) {
        String temp = mlInputs.get(index);
        if (null != temp) {
            trainings.add(new UserInputTrainingRecord(" ", temp));
        }
    }

    FileWriter fileWriter = null; // NOPMD

    CSVPrinter csvFilePrinter = null; // NOPMD

    // Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = getCSVFormat();
    try {

        // initialize FileWriter object
        // FileSystemResource testFile = new
        // FileSystemResource(UserInputsTrainer.TESTFILE);

        fileWriter = new FileWriter(UserInputsTrainer.TESTFILE, append);

        // initialize CSVPrinter object
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);// NOPMD

        // Write a new student object list to the CSV file
        for (UserInputTrainingRecord student : trainings) {
            List<String> studentDataRecord = new ArrayList<String>();
            studentDataRecord.add(student.getInputLabelName());
            studentDataRecord.add(student.getInputMLHtmlCode());
            csvFilePrinter.printRecord(studentDataRecord);
        }

        // System.out.println("CSV file was created successfully !!!");

    } catch (Exception e) {// NOPMD
        throw new IOException("Error in CsvFileWriter !!!");// NOPMD
        // e.printStackTrace();
    } finally {// NOPMD
        try {
            if (null != fileWriter) {
                fileWriter.flush();
                fileWriter.close();

            }
            if (null != csvFilePrinter) {
                csvFilePrinter.close();
            }
        } catch (IOException e) { // NOPMD
            throw new IOException(//NOPMD
                    "Error while flushing/closing fileWriter/csvPrinter !!!"); // NOPMD
            // e.printStackTrace();
        }
    }
}

From source file:ddf.catalog.transformer.csv.CsvQueryResponseTransformer.java

private void printData(final CSVPrinter csvPrinter, final Iterator iterator) {
    try {/*ww  w . ja v  a  2  s . c  o m*/
        csvPrinter.printRecord(() -> iterator);
    } catch (IOException ioe) {
        LOGGER.error(ioe.getMessage(), ioe);
    }
}

From source file:edu.uri.egr.hermes.manipulators.FileLog.java

public void flush() {
    try {/*from w  w  w  .java 2s.  c o m*/
        CSVPrinter printer = CSVFormat.EXCEL.print(new BufferedWriter(new FileWriter(file, true)));

        printer.printRecord(valuePool);
        printer.close();

        if (enableAutoVisible)
            Hermes.File.makeVisible(file);
    } catch (IOException e) {
        Timber.e("Failed to write log file: %s", e.getMessage());
    }
}

From source file:co.cask.hydrator.plugin.CSVFormatter.java

@Override
public void transform(StructuredRecord record, Emitter<StructuredRecord> emitter) throws Exception {
    List<Object> values = Lists.newArrayList();
    for (Schema.Field field : record.getSchema().getFields()) {
        values.add(record.get(field.getName()));
    }//from w  ww.  j av a  2s . co  m

    CSVPrinter printer = new CSVPrinter(new StringWriter(), csvFileFormat);
    if (printer != null) {
        printer.printRecord(values);
        emitter.emit(StructuredRecord.builder(outSchema)
                .set(outSchema.getFields().get(0).getName(), printer.getOut().toString()).build());
        printer.close();
    }
}

From source file:com.chargebee.CSV.RemovingDuplicateEntries.java

private void remove(CSVParser parser, CSVPrinter printer) throws Exception {

    List<String> list = new ArrayList();
    for (CSVRecord record : parser) {
        String tempo = "";
        String[] s = toArray(record);
        for (String val : s) {
            tempo = tempo + val;
        }//from w  w w. j  ava 2  s .c  o  m
        if (!list.contains(tempo)) {
            list.add(tempo);
            printer.printRecord(record);
        }
    }
}

From source file:de.speexx.jira.jan.command.issuequery.CsvCreator.java

void printHeader(final List<FieldNamePath> currentFieldNames, final List<FieldName> historyFieldNames,
        final TemporalChangeOutput temporalOutput) {
    assert !Objects.isNull(currentFieldNames);
    assert !Objects.isNull(historyFieldNames);
    assert !Objects.isNull(temporalOutput);

    final List<String> headerNames = new ArrayList<>();
    currentFieldNames.stream().map(FieldNamePath::asString)
            .map(name -> name.replaceAll(FieldNamePath.DELIMITER, FIELDNAMEPATH_DELIMITER_REPALCEMENT))
            .forEach(name -> headerNames.add(name));
    historyFieldNames.stream().map(FieldName::asString).forEach(name -> {
        headerNames.add(HOSTORICAL_FROM_PREFIX + name);
        if (temporalOutput != NONE) {
            if (temporalOutput == BOTH || temporalOutput == TIME) {
                headerNames.add(HOSTORICAL_CHANGE_DATETIME_PREFIX + name);
            }// ww w  .jav  a2s  .c  o  m
            if (temporalOutput == BOTH || temporalOutput == DURATION) {
                headerNames.add(HOSTORICAL_DURATION_PREFIX + name);
            }
        }
        headerNames.add(HOSTORICAL_TO_PREFIX + name);
    });
    try {
        final CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8),
                RFC4180);
        csvPrinter.printRecord(headerNames.toArray());
        csvPrinter.flush();
    } catch (final IOException e) {
        throw new JiraAnalyzeException(e);
    }
}

From source file:com.goeuro.goeurotest.service.Services.java

/**
 * Write CSV file using list of records and pre defined static header
 *
 * @param recordsList/* w  ww . ja v  a  2s.  co  m*/
 * @throws Exception
 */
public void writeCSV(List recordsList) throws Exception {
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(Defines.NEW_LINE_SEPARATOR);
        fileWriter = new FileWriter(Defines.FILE_NAME);
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
        csvFilePrinter.printRecord(Defines.FILE_HEADER);
        for (Object recordList : recordsList) {
            csvFilePrinter.printRecords(recordList);
        }
        fileWriter.flush();
        fileWriter.close();
        csvFilePrinter.close();
    } catch (IOException ex) {
        throw new Exception("IOException occured while writing CSV file " + ex.getMessage());
    }
}

From source file:com.test.goeuro.csvGenerator.CSVFileGenerator.java

/**
 *
 * @param respondArray/*  w  w w .ja va2 s .  co m*/
 */
public void createCSVFileAndWriteData(JsonArray respondArray) throws FileNotFoundException, IOException {

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    CSVFormat csvFileFormat = CSVFormat.EXCEL.withRecordSeparator(NEW_LINE_SEPARATOR);
    try {
        System.out.println("generating CVS file ....");
        fileWriter = new FileWriter(new File(Constants.FILE_NAME));
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
        csvFilePrinter.printRecord(FILE_HEADER);

        for (JsonElement jsonElement : respondArray) {
            List apiRespondData = new ArrayList();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            apiRespondData.add(jsonObject.get(Constants._ID).getAsString());
            apiRespondData.add(jsonObject.get(Constants.NAME).getAsString());
            apiRespondData.add(jsonObject.get(Constants.TYPE).getAsString());
            JsonObject inGeoPosObject = jsonObject.getAsJsonObject(Constants.GEO_POSITION);
            apiRespondData.add(inGeoPosObject.get(Constants.LATITUDE).getAsDouble());
            apiRespondData.add(inGeoPosObject.get(Constants.LONGITUDE).getAsDouble());
            csvFilePrinter.printRecord(apiRespondData);
        }

        System.out.println("CSV generated successfully");
    } catch (FileNotFoundException fnfex) {
        Logger.getLogger(CSVFileGenerator.class.getName()).log(Level.SEVERE, null, fnfex);
        System.out.println("Error in Open csv file");
        fnfex.printStackTrace();
    } catch (IOException ioex) {
        Logger.getLogger(CSVFileGenerator.class.getName()).log(Level.SEVERE, null, ioex);
        System.out.println("Error in Open/Write CsvFileWriter!!!");
        ioex.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            e.printStackTrace();
        } catch (Exception ex) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            ex.printStackTrace();
        }
    }
}

From source file:com.github.r351574nc3.amex.assignment1.csv.DefaultGenerator.java

public void generate(final File output, final Integer recordCount) throws IOException {

    final CSVPrinter printer = new CSVPrinter(new FileWriter(output), CSVFormat.RFC4180.withDelimiter('|'));
    try {/*from   w  w w . j a va2s.c o  m*/
        for (final Iterator<TestData> data_iter = testContentService.generate(recordCount); data_iter
                .hasNext();) {
            final TestData record = data_iter.next();
            debug("Printing record: %s", record.asList().get(0));
            printer.printRecord(record.asList());
        }
    } finally {
        if (printer != null) {
            try {
                printer.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.streamsets.pipeline.kafka.common.SdcKafkaTestUtil.java

public List<KeyedMessage<String, String>> produceCsvMessages(String topic, String partition,
        CSVFormat csvFormat, File csvFile) throws IOException {
    List<KeyedMessage<String, String>> messages = new ArrayList<>();
    String line;/*from w ww . j ava  2s . c om*/
    BufferedReader bufferedReader = new BufferedReader(
            new FileReader(KafkaTestUtil.class.getClassLoader().getResource("testKafkaTarget.csv").getFile()));
    while ((line = bufferedReader.readLine()) != null) {
        String[] strings = line.split(",");
        StringWriter stringWriter = new StringWriter();
        CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
        csvPrinter.printRecord(strings);
        csvPrinter.flush();
        csvPrinter.close();
        messages.add(new KeyedMessage<>(topic, partition, stringWriter.toString()));
    }
    return messages;
}