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

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

Introduction

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

Prototype

@Override
    public void close() throws IOException 

Source Link

Usage

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.util.TrainingDataUtils.java

/**
 * Converts a training like argument list to a CSV representation.
 * /* ww w  . j ava  2 s .  com*/
 * @param data
 *            the training data data
 * @return the string with the CSV representation for the training data
 */
public static String toCSV(final TrainingData... data) {
    Validate.notEmpty(data, "data cannot be null or empty");

    StringWriter stringWriter = new StringWriter();
    try {
        CSVPrinter printer = new CSVPrinter(stringWriter, CSVFormat.EXCEL);
        for (TrainingData trainingData : data) {
            if (trainingData.getText() == null || trainingData.getClasses() == null
                    || trainingData.getClasses().isEmpty())
                log.log(Level.WARNING, trainingData + " couldn't be converted to a csv record");
            else {
                List<String> record = new ArrayList<String>();
                record.add(trainingData.getText());
                record.addAll(trainingData.getClasses());
                printer.printRecord(record.toArray());
            }
        }
        printer.close();
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error creating the csv", e);
    }

    return stringWriter.toString();
}

From source file:com.fbartnitzek.tasteemall.data.csv.CsvFileWriter.java

public static String writeFile(String[] headers, List<List<String>> entries, File file) {

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    String msg = null;// ww w.j  a v a  2  s . c o m
    try {
        fileWriter = new FileWriter(file); //initialize FileWriter object
        csvFilePrinter = new CSVPrinter(fileWriter, CSV_FORMAT_RFC4180); //initialize CSVPrinter object
        csvFilePrinter.printRecord(Arrays.asList(headers)); //Create CSV file header

        //Write a new student object list to the CSV file
        for (List<String> dataEntry : entries) {
            csvFilePrinter.printRecord(dataEntry);
        }

    } catch (Exception e) {
        e.printStackTrace();
        msg = "Error in CsvFileWriter !!!";
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            msg = "Error while flushing/closing fileWriter/csvPrinter !!!";

        }
    }
    return msg;
}

From source file:cz.pichlik.goodsentiment.MockDataGenerator.java

private static void generateFile(File file, LocalDate date) throws IOException {
    CSVFormat format = CSVFormat//from ww w .jav a  2  s  .c o  m
            .newFormat(',').withRecordSeparator("\r\n").withQuote('"').withHeader("id", "sentimentCode",
                    "orgUnit", "latitude", "longitude", "city", "gender", "yearsInCompany", "timestamp")
            .withNullString("");

    CSVPrinter printer = null;
    try (OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file))) {
        printer = new CSVPrinter(output, format);
        for (int i = 0; i < 150 + rg().nextInt(100); i++) {
            long id = sequence++;
            int sentimentCode = generateSentiment();
            String orgUnit = generateOrgUnit();
            Object geo[] = generateGeo();
            Object latitude = geo[0];
            Object longitude = geo[1];
            Object city = geo[2];
            String gender = generateGender();
            int daysInCompany = generateYearsInCompany();
            LocalDateTime timestamp = generateTimestamp(date);
            printer.printRecord(id, sentimentCode, orgUnit, latitude, longitude, city, gender, daysInCompany,
                    timestamp);
        }
    } finally {
        printer.close();
    }
}

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

/**
 * Write cache csv file.//from  w w  w .jav a  2s  . c om
 *
 * @param absoluteCacheFilePath
 *            the absolute cache file path
 * @param beginningComments
 *            the beginning comments
 * @param endingComments
 *            the ending comments
 * @param trainedRecords
 *            the trained records
 * @param append
 *            the append
 * @throws IOException
 */
public static void writeCacheCsvFile(String absoluteCacheFilePath, String beginningComments,
        String endingComments, List<UserInputTrainingRecord> trainedRecords, boolean append)
        throws IOException {
    // Create new students objects

    FileWriter fileWriter = null;// NOPMD

    CSVPrinter csvFilePrinter = null;// NOPMD

    // Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = getCSVFormat();
    try {
        if (trainedRecords.isEmpty()) {
            fileWriter = new FileWriter(absoluteCacheFilePath, append);

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

            // Write a new student object list to the CSV file
            csvFilePrinter.printComment(beginningComments);
            csvFilePrinter.printComment(endingComments);

            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
            return;
        }

        // initialize FileWriter object
        fileWriter = new FileWriter(absoluteCacheFilePath, append);

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

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

            csvFilePrinter.printRecord(studentDataRecord);
        }
        csvFilePrinter.printComment(endingComments);
        // 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
            //System.out
            throw new IOException("Error while flushing/closing fileWriter/csvPrinter !!!");//NOPMD
            //e.printStackTrace();
        }
    }
}

From source file:com.ibm.watson.app.common.tagEvent.TagRecord.java

public String asCsv() {
    prepareForFormat();//  w w w .j  av  a  2 s  .  c o  m
    StringBuilder sb = new StringBuilder();
    try {
        CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT);
        printer.printRecord(this);
        printer.close();
    } catch (IOException e) {

    }
    return sb.toString();

}

From source file:com.leadscope.commanda.maps.CSVLineMap.java

@Override
public String apply(List<String> element) {
    StringWriter sw = new StringWriter();
    try {/*  www  .j  av  a 2s  .c om*/
        CSVPrinter printer = new CSVPrinter(sw, noBreakFormat);
        printer.printRecord(element);
        printer.close();
        return sw.toString();
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.github.hebra.elasticsearch.beat.meterbeat.service.CSVFileOutputService.java

@Override
public synchronized void send(BeatOutput output) {
    if (isEnable()) {

        try (PrintWriter writer = new PrintWriter(new FileOutputStream(outputPath.toFile(), true))) {
            CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter).withQuote(quote)
                    .withQuoteMode(QuoteMode.NON_NUMERIC).withSkipHeaderRecord(true);

            CSVPrinter csvFilePrinter = new CSVPrinter(writer, csvFileFormat);
            csvFilePrinter.printRecord(output.asIterable());
            csvFilePrinter.close();
        } catch (IOException ioEx) {
            log.error(ioEx.getMessage());
        }/*from www  .ja  va  2s .  c o  m*/
    }
}

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

public void flush() {
    try {//from   w  w w. ja v  a 2  s.  c om
        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:com.hys.enterprise.dominoes.reporting.ReportBuilder.java

/**
 * Writes record to csv file/* w w  w.  j  a v a2 s  .c om*/
 * @param record
 * @throws IOException
 */
public void writeRecord(ReportRecord record) throws IOException {
    fileWriter = new FileWriter(file, true);
    CSVPrinter csvFilePrinter;
    csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
    if (!file.exists() || file.length() == 0) {
        csvFilePrinter.printRecord(record.getHeader());
    }
    csvFilePrinter.printRecord(record.getData());

    if (fileWriter != null) {
        fileWriter.flush();
        fileWriter.close();
    }
    csvFilePrinter.close();
}

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   ww  w .  ja  v a 2  s. c om*/

    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();
    }
}