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:com.spectralogic.ds3cli.views.csv.CsvOutput.java

public String toString() {
    try (final StringWriter writer = new StringWriter();
            final CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL)) {

        csvPrinter.printRecord(headers);
        for (final E content : csvContents) {
            csvPrinter.printRecord(contentFormatter.format(content));
        }//from w ww . ja v  a2s  . c o  m
        return writer.toString();
    } catch (final IOException e) {
        throw new RuntimeException("Failed to write csv", e);
    }
}

From source file:com.datascience.hadoop.CsvRecordWriter.java

public CsvRecordWriter(Writer writer, CSVFormat format) throws IOException {
    out = new CSVPrinter(writer, format);
}

From source file:io.ecarf.core.compress.callback.CommonsCsvCallback.java

@Override
public void setOutput(Appendable out) throws IOException {
    this.printer = new CSVPrinter(out, CSVFormat.DEFAULT);
}

From source file:com.amazonaws.services.dynamodbv2.online.index.ViolationWriter.java

public void createOutputFile(String outputFilePath) throws IOException {
    File outputFile = new File(outputFilePath);
    if (outputFile.exists()) {
        outputFile.delete();//from   www . j a v  a2 s .  c  o  m
    }
    outputFile.createNewFile();
    FileWriter out = new FileWriter(outputFilePath, true);
    bufferWriter = new BufferedWriter(out);
    printer = new CSVPrinter(bufferWriter, format);
}

From source file:javalibs.CSVExtractor.java

/**
 * Writes the CSV to the path specified in the c'tor. Returns the absolute path to
 * the output CSV file/*from w ww .  j  ava  2 s .c o  m*/
 * @return The absolute path to the output CSV file
 */
public String writeCSV() {
    BufferedWriter bw = null;
    CSVPrinter printer = null;

    try {
        bw = Files.newBufferedWriter(Paths.get(this.outCSV));
        printer = new CSVPrinter(bw, CSVFormat.DEFAULT.withHeader(this.orderedExtractionCols));
    } catch (IOException e) {
        log_.die(e);
    }

    log_.require(bw != null, "BufferedWriter cannot be null");
    log_.require(printer != null, "CSVPrinter cannot be null");

    for (CSVRecord rec : this.inRecords) {
        List<String> writerCells = new ArrayList<>();
        for (String col : this.headersInOrder) {
            if (!this.extractionCols.contains(col))
                continue;

            String colVal = null;
            try {
                colVal = rec.get(col);
            } catch (IllegalArgumentException e) {
                log_.err("Could not find column: " + col);
                log_.die(e);
            }
            writerCells.add(colVal);
        }
        try {
            printer.printRecord(writerCells.toArray());
        } catch (IOException e) {
            log_.die(e);
        }
    }
    try {
        printer.flush();
    } catch (IOException e) {
        log_.die(e);
    }

    return new File(this.outCSV).getAbsolutePath();
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.evaluation.GenerateCrossDomainCVReport.java

/**
 * Merges id2outcome files from sub-folders with cross-domain and creates a new folder
 * with overall results/*from  www .j  a  v a  2  s  .  c  om*/
 *
 * @param folder folder
 * @throws java.io.IOException
 */
public static void aggregateDomainResults(File folder, String subDirPrefix, final String taskFolderSubText,
        String outputFolderName) throws IOException {
    // list all sub-folders
    File[] folders = folder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && pathname.getName().contains(taskFolderSubText);
        }
    });

    if (folders.length == 0) {
        throw new IllegalArgumentException("No sub-folders 'SVMHMMTestTask*' found in " + folder);
    }

    // write to a file
    File outFolder = new File(folder, outputFolderName);
    File output = new File(outFolder, subDirPrefix);
    output.mkdirs();

    File outCsv = new File(output, TOKEN_LEVEL_PREDICTIONS_CSV);

    CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(outCsv), SVMHMMUtils.CSV_FORMAT);
    csvPrinter.printComment(SVMHMMUtils.CSV_COMMENT);

    ConfusionMatrix cm = new ConfusionMatrix();

    for (File domain : folders) {
        File tokenLevelPredictionsCsv = new File(domain, subDirPrefix + "/" + TOKEN_LEVEL_PREDICTIONS_CSV);

        if (!tokenLevelPredictionsCsv.exists()) {
            throw new IllegalArgumentException(
                    "Cannot locate tokenLevelPredictions.csv: " + tokenLevelPredictionsCsv);
        }

        CSVParser csvParser = new CSVParser(new FileReader(tokenLevelPredictionsCsv),
                CSVFormat.DEFAULT.withCommentMarker('#'));

        for (CSVRecord csvRecord : csvParser) {
            // copy record
            csvPrinter.printRecord(csvRecord);

            // update confusion matrix
            cm.increaseValue(csvRecord.get(0), csvRecord.get(1));
        }
    }

    // write to file
    FileUtils.writeStringToFile(new File(outFolder, "confusionMatrix.txt"), cm.toString() + "\n"
            + cm.printNiceResults() + "\n" + cm.printLabelPrecRecFm() + "\n" + cm.printClassDistributionGold());

    // write csv
    IOUtils.closeQuietly(csvPrinter);
}

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  ww  w  .j  av a2s . co 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:ddf.catalog.transformer.csv.common.CsvTransformer.java

public static Appendable writeMetacardsToCsv(final List<Metacard> metacards,
        final List<AttributeDescriptor> orderedAttributeDescriptors, final Map<String, String> aliasMap)
        throws CatalogTransformerException {
    StringBuilder stringBuilder = new StringBuilder();

    try {//  w w w  .j ava2 s.c o m
        CSVPrinter csvPrinter = new CSVPrinter(stringBuilder, CSVFormat.RFC4180);
        printColumnHeaders(csvPrinter, orderedAttributeDescriptors, aliasMap);

        metacards.forEach(metacard -> printMetacard(csvPrinter, metacard, orderedAttributeDescriptors));

        return csvPrinter.getOut();
    } catch (IOException ioe) {
        throw new CatalogTransformerException(ioe);
    }
}

From source file:edu.caltech.ipac.firefly.server.util.DsvToDataGroup.java

public static void write(Writer writer, DataGroup data, CSVFormat format) throws IOException {

    BufferedWriter outf = new BufferedWriter(writer, IpacTableUtil.FILE_IO_BUFFER_SIZE);
    try {//from   ww  w .ja v a2  s.  com
        CSVPrinter printer = new CSVPrinter(outf, format);

        if (data != null && data.size() > 0) {
            for (DataType t : data.getDataDefinitions()) {
                printer.print(t.getKeyName());
            }
            printer.println();

            for (DataObject row : data.values()) {
                for (String s : row.getFormatedData()) {
                    printer.print(s.trim());
                }
                printer.println();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outf != null) {
            outf.close();
        }
    }
}

From source file:com.qwazr.library.csv.CSVTool.java

@JsonIgnore
public CSVPrinter getNewPrinter(CSVFormat format, Appendable appendable, IOUtils.CloseableContext closeable)
        throws IOException {
    CSVPrinter printer = new CSVPrinter(appendable, format);
    if (closeable != null)
        closeable.add(printer);/*  w ww  .j a va  2 s .co m*/
    return printer;
}