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

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

Introduction

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

Prototype

public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException 

Source Link

Document

Creates a printer that will print values to the given stream following the CSVFormat.

Usage

From source file:net.sourceforge.ganttproject.io.GanttCSVExport.java

/**
 * Save the project as CSV on a stream/*from  w  w  w.j  av a  2s  .  c  om*/
 *
 * @throws IOException
 */
public void save(OutputStream stream) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream);
    CSVFormat format = CSVFormat.DEFAULT.withEscape('\\');
    if (csvOptions.sSeparatedChar.length() == 1) {
        format = format.withDelimiter(csvOptions.sSeparatedChar.charAt(0));
    }
    if (csvOptions.sSeparatedTextChar.length() == 1) {
        format = format.withEncapsulator(csvOptions.sSeparatedTextChar.charAt(0));
    }

    CSVPrinter csvPrinter = new CSVPrinter(writer, format);

    if (csvOptions.bFixedSize) {
        // TODO The CVS library we use is lacking support for fixed size
        getMaxSize();
    }

    writeTasks(csvPrinter);

    if (myProject.getHumanResourceManager().getResources().size() > 0) {
        csvPrinter.println();
        csvPrinter.println();
        writeResources(csvPrinter);
    }
    writer.flush();
    writer.close();
}

From source file:io.heming.accountbook.util.Importer.java

public int exportRecords(File file) throws Exception {
    int count = 0;
    try (Writer out = new FileWriter(file)) {
        CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withQuote('"'));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Record> records = recordFacade.list();
        int total = records.size();
        for (Record record : records) {
            Integer id = record.getId();
            String category = record.getCategory().getName();
            Double price = record.getPrice();
            String phone = record.getPhone();
            String date = format.format(record.getDate());
            String note = record.getNote();
            printer.printRecord(id, category, price, phone, date, note);
            count++;/*from  w  w  w. j a v a  2s  . c om*/
        }
    }
    return count;
}

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();//  w w w .ja va2  s .c o m
        } catch (IOException ioEx) {
            log.error(ioEx.getMessage());
        }
    }
}

From source file:net.ageto.gyrex.logback.extensions.csv.CsvEncoder.java

@Override
public void init(final OutputStream os) throws IOException {
    super.init(os);

    if ((outputStream != null) && (csvFormat != null)) {
        final PrintStream printStream = new PrintStream(outputStream, false,
                charset != null ? charset.name() : "UTF-8");
        csvPrinter = new CSVPrinter(printStream, csvFormat);
    }/* www  .  j ava 2  s  . c  o m*/
}

From source file:fr.cea.ig.grools.reporter.CSVReport.java

public CSVReport(@NonNull final File file) throws IOException {
    super(file);/*from w w  w .  ja v  a 2 s .c o  m*/
    this.csvPrinter = new CSVPrinter(bos, format);
    csvPrinter.printRecord(header);
}

From source file:licenseUtil.LicensingList.java

public void writeToSpreadsheet(String spreadsheetFN) throws IOException {
    logger.info("write spreadsheet to \"" + spreadsheetFN + "\"");
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;/*from w  w w  . j a  va2  s .co m*/

    //Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withDelimiter(columnDelimiter);

    try {
        //initialize FileWriter object
        fileWriter = new FileWriter(spreadsheetFN);

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

        ArrayList<String> headers = new ArrayList<>();
        headers.addAll(LicensingObject.ColumnHeader.HEADER_VALUES);
        headers.addAll(getNonFixedHeaders());
        //Create CSV file header
        csvFilePrinter.printRecord(headers);
        for (LicensingObject licensingObject : this) {
            csvFilePrinter.printRecord(licensingObject.getRecord(headers));
        }
        logger.info("CSV file was created successfully");

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

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.evaluation.ResultWriter.java

@Override
public void initialize(Properties properties) {
    // Retrieve necessary properties
    String resultsFilePath = properties.getProperty(ConfigurationConstants.PIPELINE_RESULTS_TSV_FILE_PATH);
    this.format = PipelineResultsTsvFileFormats
            .valueOf(properties.getProperty(ConfigurationConstants.PIPELINE_RESULTS_TSV_FILE_FORMAT,
                    PipelineResultsTsvFileFormats.DEFAULT.toString()));

    // Make sure file path was actually specified
    if (resultsFilePath == null)
        throw new RuntimeException(MessageFormat.format(Messages.getString("RetrieveAndRank.MISSING_PROPERTY"), //$NON-NLS-1$
                ConfigurationConstants.PIPELINE_RESULTS_TSV_FILE_FORMAT));

    // Open a FileWriter, using CSV or TSV format depending on desired
    // output format
    try {/*from   ww  w  . j a  va2s .co  m*/
        writer = (this.format == PipelineResultsTsvFileFormats.COMPETITION)
                ? new CSVPrinter(new FileWriter(resultsFilePath), CSVFormat.DEFAULT)
                : new CSVPrinter(new FileWriter(resultsFilePath),
                        CSVFormat.TDF.withHeader(getHeaders(this.format)));
    } catch (IOException e) {
        throw new RuntimeException(new PipelineException(e));
    }
}

From source file:com.nordpos.device.csv.FileCSVInputOutput.java

@Override
public void startUploadProduct() throws DeviceInputOutputException {
    try {/*from  w w w  .ja  v  a 2 s.  com*/
        fileWriter = new FileWriter(outFile);
        csvPrinter = new CSVPrinter(fileWriter, format);
    } catch (IOException ex) {
        throw new DeviceInputOutputException(ex);
    }
}

From source file:dk.dma.ais.packet.AisPacketCSVOutputSink.java

@Override
public void process(OutputStream stream, AisPacket packet, long count) throws IOException {

    csvLock.lock();//from  ww w  .  j a v  a  2 s . c  om
    try {
        if (csv == null) {
            csv = new CSVPrinter(new OutputStreamWriter(stream), CSVFormat.DEFAULT.withHeader(columns));
        }

        AisMessage m = packet.tryGetAisMessage();
        if (m != null) {
            List fields = Lists.newArrayList();

            for (String column : columns) {
                switch (column) {
                case "timestamp":
                    addTimestamp(fields, packet);
                    break;
                case "timestamp_pretty":
                    addTimestampPretty(fields, packet);
                    break;
                case "msgid":
                    addMsgId(fields, m);
                    break;
                case "mmsi":
                    addMmsi(fields, m);
                    break;
                case "posacc":
                    addPositionAccuracy(fields, m);
                    break;
                case "lat":
                    addLatitude(fields, m);
                    break;
                case "lon":
                    addLongitude(fields, m);
                    break;
                case "targetType":
                    addTargetType(fields, m);
                    break;
                case "sog":
                    addSog(fields, m);
                    break;
                case "cog":
                    addCog(fields, m);
                    break;
                case "trueHeading":
                    addTrueHeading(fields, m);
                    break;
                case "draught":
                    addDraught(fields, m);
                    break;
                case "name":
                    addName(fields, m);
                    break;
                case "dimBow":
                    addDimBow(fields, m);
                    break;
                case "dimPort":
                    addDimPort(fields, m);
                    break;
                case "dimStarboard":
                    addDimStarboard(fields, m);
                    break;
                case "dimStern":
                    addDimStern(fields, m);
                    break;
                case "shipTypeCargoTypeCode":
                    addShipTypeCargoTypeCode(fields, m);
                    break;
                case "shipType":
                    addShipType(fields, m);
                    break;
                case "shipCargo":
                    addShipCargo(fields, m);
                    break;
                case "callsign":
                    addCallsign(fields, m);
                    break;
                case "imo":
                    addImo(fields, m);
                    break;
                case "destination":
                    addDestination(fields, m);
                    break;
                case "eta":
                    addEta(fields, m);
                    break;
                default:
                    LOG.warn("Unknown column: " + column);
                    fields.add(NULL_INDICATOR);
                }
            }

            csv.printRecord(fields);
        }
    } finally {
        csvLock.unlock();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.report.SVMHMMBatchCrossValidationReport.java

protected void aggregateResults(String testTaskCSVFile, String outputPrefix) throws Exception {
    StorageService storageService = getContext().getStorageService();

    // aggregate rows from all CSVs from all folds
    List<List<String>> allOutcomes = new ArrayList<>();

    List<TaskContextMetadata> testTasks = collectTestTasks();

    // we need test tasks!
    if (testTasks.isEmpty()) {
        throw new IllegalStateException("No test tasks found. Make sure you properly "
                + "define the test task in getTestTaskClass() (currently: " + getTestTaskClass().getName());
    }/* w w w  . j  av  a2  s  .com*/

    // iterate over all sub tasks
    for (TaskContextMetadata subContext : testTasks) {
        // locate CSV file with outcomes (gold, predicted, token, etc.)
        File csvFile = storageService.getStorageFolder(subContext.getId(),
                Constants.TEST_TASK_OUTPUT_KEY + File.separator + testTaskCSVFile);

        // load the CSV
        CSVParser csvParser = new CSVParser(new FileReader(csvFile), CSVFormat.DEFAULT.withCommentMarker('#'));

        // and add the all rows
        for (CSVRecord csvRecord : csvParser) {
            // row for particular instance
            List<String> row = new ArrayList<>();
            for (String value : csvRecord) {
                row.add(value);
            }
            allOutcomes.add(row);
        }

        IOUtils.closeQuietly(csvParser);
    }

    // store aggregated outcomes again to CSV
    File evaluationFile = new File(getContext().getStorageLocation(Constants.TEST_TASK_OUTPUT_KEY,
            StorageService.AccessMode.READWRITE), testTaskCSVFile);
    log.debug("Evaluation file: " + evaluationFile.getAbsolutePath());

    CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(evaluationFile), SVMHMMUtils.CSV_FORMAT);
    csvPrinter.printComment(SVMHMMUtils.CSV_COMMENT);
    csvPrinter.printRecords(allOutcomes);
    IOUtils.closeQuietly(csvPrinter);

    // compute confusion matrix
    ConfusionMatrix cm = new ConfusionMatrix();

    for (List<String> singleInstanceOutcomeRow : allOutcomes) {
        // first item is the gold label
        String gold = singleInstanceOutcomeRow.get(0);
        // second item is the predicted label
        String predicted = singleInstanceOutcomeRow.get(1);

        cm.increaseValue(gold, predicted);
    }

    // and write all reports
    SVMHMMUtils.writeOutputResults(getContext(), cm, outputPrefix);

    // and print detailed results
    log.info(outputPrefix + "; " + cm.printNiceResults());
    log.info(outputPrefix + "; " + cm.printLabelPrecRecFm());
}