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:br.edimarmanica.trinity.intrasitemapping.manual.AllMappings.java

private void print(List<String> dataRecord) {
    /**/*from   www . j a va 2  s . co  m*/
     * ********************** results ******************
     */
    File dir = new File(Paths.PATH_TRINITY + "/" + site.getPath());
    dir.mkdirs();

    File file = new File(dir.getAbsolutePath() + "/mappings.csv");
    CSVFormat format;
    if (append) {
        format = CSVFormat.EXCEL;
    } else {
        format = CSVFormat.EXCEL.withHeader(header);
    }

    try (Writer out = new FileWriter(file, append)) {
        try (CSVPrinter csvFilePrinter = new CSVPrinter(out, format)) {
            csvFilePrinter.printRecord(dataRecord);
        }
    } catch (IOException ex) {
        Logger.getLogger(Printer.class.getName()).log(Level.SEVERE, null, ex);
    }

    append = true;
}

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

public void files(Collection<ICloud.MBSFile> files, Path path) throws IOException {
    logger.trace("<< write() < files: {} path: {}", files.size(), path);

    Files.createDirectories(path.getParent());

    try (CSVPrinter printer = new CSVPrinter(new FileWriter(path.toFile()), csvFormat)) {
        printer.printRecord(HEADER);//  w w w  .ja  v  a  2s. c om

        for (ICloud.MBSFile file : files) {
            String mode = file.getAttributes().hasMode()
                    ? "0x" + Integer.toString(file.getAttributes().getMode(), 16)
                    : "";
            String size = file.hasSize() ? Long.toString(file.getSize()) : "";
            String lastModified = file.getAttributes().hasLastModified()
                    ? Long.toString(file.getAttributes().getLastModified())
                    : "";

            printer.print(mode);
            printer.print(size);
            printer.print(lastModified);
            printer.print(file.getDomain());
            printer.print(file.getRelativePath());
            printer.println();
        }
    }
    logger.trace(">> write()");
}

From source file:mSearch.filmlisten.WriteFilmlistJson.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {

    ZipOutputStream zipOutputStream = null;
    XZOutputStream xZOutputStream = null;
    JsonGenerator jg = null;/* ww  w. j a  va  2 s . com*/

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {
        Log.sysLog("Filme schreiben (" + listeFilme.size() + " Filme) :");
        File file = new File(datei);
        File dir = new File(file.getParent());
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                Log.errorLog(915236478, "Kann den Pfad nicht anlegen: " + dir.toString());
            }
        }
        Log.sysLog("   --> Start Schreiben nach: " + datei);

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withDelimiter(';').withQuote('\'')
                .withRecordSeparator("\n");
        fileWriter = new FileWriter(datei);
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        // Infos der Felder in der Filmliste
        csvFilePrinter.printRecord(DatenFilm.COLUMN_NAMES);

        //Filme schreiben
        DatenFilm datenFilm;
        Iterator<DatenFilm> iterator = listeFilme.iterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            datenFilm.arr[DatenFilm.FILM_NEU] = Boolean.toString(datenFilm.isNew()); // damit wirs beim nchsten Programmstart noch wissen

            List<String> filmRecord = new ArrayList<String>();
            for (int i = 0; i < DatenFilm.JSON_NAMES.length; ++i) {
                int m = DatenFilm.JSON_NAMES[i];
                filmRecord.add(datenFilm.arr[m].replace("\n", "").replace("\r", ""));
            }
            csvFilePrinter.printRecord(filmRecord);
        }
        Log.sysLog("   --> geschrieben!");
    } catch (Exception ex) {
        Log.errorLog(846930145, ex, "nach: " + datei);
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (Exception e) {
            Log.errorLog(732101201, e, "close stream: " + datei);
        }
    }
}

From source file:com.ibm.watson.catalyst.objectio.writers.CSVOutputWriter.java

@Override
public void write(final Collection<? extends IWritable> writables) {
    try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(_outFile), _encoding)) {
        try (CSVPrinter printer = new CSVPrinter(writer, FORMAT);) {
            if (_header.isPresent())
                printer.printRecord(_header.get());
            printer.printRecords(writables);
        } catch (final IOException e) {
            throw new RuntimeException("IOError writing to " + _outFile, e);
        }/*from  ww  w .j  a va 2s.  c  o  m*/
    } catch (final IOException e) {
        throw new RuntimeException("IOError opening " + _outFile + " for writing.");
    }
}

From source file:com.streamsets.pipeline.lib.util.CsvUtil.java

public static String csvRecordToString(Record r, CSVFormat csvFormat) throws IOException {
    StringWriter stringWriter = new StringWriter();
    CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
    csvPrinter.printRecord(CsvUtil.fieldToCsv(r.get()));
    csvPrinter.flush();//from www . j a v a2s .  co m
    csvPrinter.close();
    return stringWriter.toString();
}

From source file:com.act.utils.TSVWriter.java

public void open(File f) throws IOException {
    String[] headerStrings = new String[header.size()];
    for (int i = 0; i < header.size(); i++) {
        headerStrings[i] = header.get(i).toString();
    }//from  w w w .j av  a2s . com
    printer = new CSVPrinter(new FileWriter(f), TSV_FORMAT.withHeader(headerStrings));
}

From source file:com.apkcategorychecker.json.DefaultJsCSVBuilder.java

@Override
public void BuildJs(ArrayList<JsElement> jsList, String _destinationPath, String time) {

    try {//  w w  w .j  av  a  2  s. c o  m

        /*Check if _destinationPath is an APK or a Directory in order to
        *get the right destination path
        */

        File Destination = new File(_destinationPath);
        if (!Destination.exists()) {
            Destination.mkdir();
        }
        if (Destination.isDirectory()) {
            this._destPath = _destinationPath;
        } else if (Destination.isFile()) {
            this._destPath = _destinationPath.substring(0, _destinationPath.length() - 4);
        }

        /*--Create the CSVFormat object--*/

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

        /*--Writing in a CSV file--*/

        File _fileCSV = new File(_destPath + "/Results-JS FILES_" + time + ".csv");
        FileWriter _out = new FileWriter(_fileCSV);
        CSVPrinter printer;
        printer = new CSVPrinter(_out, format.withDelimiter('#'));
        System.out.println("Creating " + "Results-JS FILES_" + time + ".csv ....");
        try {
            printer.printRecord("appID", "jsFiles");
        } catch (IOException ex) {
            Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex);
        }

        /*--Retrieve APKResult and Write in file--*/

        @SuppressWarnings("unused")
        int i = 0;
        Iterator<JsElement> it = jsList.iterator();
        while (it.hasNext()) {
            JsElement _resultElement = it.next();
            List<String> resultData = new ArrayList<>();
            resultData.add(_resultElement.get_Id());
            resultData.add(_resultElement.get_JsFiles());
            i++;
            printer.printRecord(resultData);
        }

        /*--Close the printer--*/
        printer.close();
        System.out.println("Results-JS FILES_" + time + ".csv created");

    } catch (IOException ex) {
        Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.sequence.report.TokenLevelEvaluationReport.java

@Override
public void execute() throws Exception {
    // load gold and predicted labels
    loadGoldAndPredictedLabels();//from w  ww  .  ja  va  2 s.  c o m

    File testFile = locateTestFile();

    // sequence IDs
    List<Integer> sequenceIDs = SVMHMMUtils.extractOriginalSequenceIDs(testFile);

    // meta data original
    List<SortedMap<String, String>> metaDataFeatures = SVMHMMUtils.extractMetaDataFeatures(testFile);

    // sanity check
    if (goldLabels.size() != sequenceIDs.size() || goldLabels.size() != metaDataFeatures.size()) {
        throw new IllegalStateException("check consistency");
    }

    File evaluationFile = new File(
            getContext().getStorageLocation(TEST_TASK_OUTPUT_KEY, StorageService.AccessMode.READWRITE),
            TOKEN_LEVEL_PREDICTIONS_CSV);

    // write results into CSV
    // form: gold;predicted;token;seqID
    CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(evaluationFile), SVMHMMUtils.CSV_FORMAT);
    csvPrinter.printComment(SVMHMMUtils.CSV_COMMENT);

    // confusion matrix for evaluation
    ConfusionMatrix confusionMatrix = new ConfusionMatrix();

    for (int i = 0; i < goldLabels.size(); i++) {
        String predictedLabelSentenceLevel = predictedLabels.get(i);

        // get gold token labels for this sentence
        List<String> goldTokenLabels = AbstractSequenceMetaDataFeatureGenerator.decodeFromString(
                metaDataFeatures.get(i).get(OrigBIOTokenSequenceMetaDataFeatureGenerator.FEATURE_NAME));
        // get tokens for this sentence
        List<String> tokens = AbstractSequenceMetaDataFeatureGenerator.decodeFromString(
                metaDataFeatures.get(i).get(OrigTokenSequenceMetaDataFeatureGenerator.FEATURE_NAME));
        // predicted token labels
        List<String> recreatedPredictedTokenLabels = ReportTools
                .recreateTokenLabels(predictedLabelSentenceLevel, goldTokenLabels.size());

        for (int j = 0; j < goldTokenLabels.size(); j++) {
            String tokenGold = goldTokenLabels.get(j);
            String tokenPredicted = recreatedPredictedTokenLabels.get(j);

            // write to csv
            csvPrinter.printRecord(tokenGold, tokenPredicted, tokens.get(j), sequenceIDs.get(i).toString());

            // add to matrix
            confusionMatrix.increaseValue(tokenGold, tokenPredicted);
        }
    }

    IOUtils.closeQuietly(csvPrinter);

    // and write to the output
    writeResults(getContext(), confusionMatrix);
}

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

public CSVSensitivitySpecificity(@NonNull final String filepath, @NonNull final Reasoner reasoner)
        throws IOException {
    super(filepath);
    this.csvPrinter = new CSVPrinter(bos, format);
    csvPrinter.printRecord(header);/*w  w w .  j a va 2 s . co  m*/
}

From source file:com.act.utils.TSVWriter.java

public void open(File f, Boolean append) throws IOException {
    if (!append) {
        open(f);/*from  www. j av a 2s  .c  o m*/
    } else {
        printer = new CSVPrinter(new FileWriter(f, true), TSV_FORMAT);
    }
}