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.team3637.service.MatchServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Match> data = getMatches();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {/*ww  w  .  j a v  a 2 s  .  c o m*/
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (Match match : data) {
            List<Object> line = new ArrayList<>();
            for (Field field : Match.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(match);
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.itemanalysis.jmetrik.file.JmetrikOutputWriter.java

private void saveCsvFile(File outputFile, Outputter outputter) throws IOException {

    ArrayList<VariableAttributes> variables = outputter.getColumnAttributes();
    LinkedHashMap<VariableName, VariableAttributes> variableAttributeMap = new LinkedHashMap<VariableName, VariableAttributes>();
    String[] header = new String[variables.size()];
    int hIndex = 0;
    for (VariableAttributes v : variables) {
        variableAttributeMap.put(v.getName(), v);
        header[hIndex] = v.getName().toString();
        hIndex++;/*from  ww w  .ja v a  2s  .c om*/
    }

    Writer writer = null;
    CSVPrinter printer = null;

    try {
        //Ensure that file is a csv file.
        String fname = FilenameUtils.removeExtension(outputFile.getAbsolutePath());
        outputFile = new File(fname + ".csv");

        writer = new OutputStreamWriter(new FileOutputStream(outputFile));
        printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withHeader(header));

        Iterator<Object[][]> iter = outputter.iterator();
        Object[][] outputChunk = null;

        while (iter.hasNext()) {
            outputChunk = iter.next();

            for (int i = 0; i < outputChunk.length; i++) {
                printer.printRecord(outputChunk[i]);
            }

        }

    } catch (IOException ex) {
        throw ex;
    } finally {
        printer.close();
    }

}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Export the configuration data into a CSV file. The CSV file may not
 * contain complete information, but is much easier for a human to work with.
 * Code will be added to allow conversion from CSV back into the JSON format.
 * //from  w w w . j a va  2  s  .  com
 * @param dir
 * @throws IOException 
 */
private void exportCsv(File dir) throws IOException {
    File file = new File(dir, "vorindex.csv");
    CSVFormat format = CSVFormat.EXCEL.withRecordSeparator("\n").withCommentMarker('#');
    FileWriter fout = new FileWriter(file);
    CSVPrinter csvOut = new CSVPrinter(fout, format);
    String[] header = { "Path", "State", "Project Name", "Project URI", "Version", "CPEs", "Project Licenses",
            "File License", "Project Description", "Digest", "Comment" };
    csvOut.printRecord((Object[]) header);

    try {
        config.exportCsv(csvOut, includeArtifacts, includeImages);
    } finally {
        fout.close();
        csvOut.close();
    }

}

From source file:mSearch.filmlisten.WriteFilmlistJson.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {

    ZipOutputStream zipOutputStream = null;
    XZOutputStream xZOutputStream = null;
    JsonGenerator jg = null;//  w  w w  . j  av  a  2s .  c  om

    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.team3637.service.TagServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Tag> data = getTags();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {/*from   w  ww .  j a  v a2  s .co m*/
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (Tag tag : data) {
            List<Object> line = new ArrayList<>();
            for (Field field : Tag.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(tag);
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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;

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

    try {//from  ww  w .  ja  va2 s.c o  m
        //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:act.installer.wikipedia.ImportantChemicalsWikipedia.java

/**
 * This function writes the important chemicals set to a TSV file.
 * @param outputPath a String indicating where the file should be written (including its name)
 *//*  ww w .  j ava2 s  .c  o  m*/
public void writeToTSV(String outputPath) {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath));
        CSVPrinter printer = new CSVPrinter(writer, TSV_FORMAT);
        printer.printComment("This file has been generated by the ImportantChemicalsWikipedia.java script.");
        printer.printComment("Format: WIKIPEDIA<tab><wikipedia url><tab><inchi><tab><metadata>");
        for (ImportantChemical importantChemical : importantChemicalsWikipedia) {
            List<String> nextLine = new ArrayList<>();
            nextLine.add(importantChemical.getType());
            nextLine.add(importantChemical.getDbid());
            nextLine.add(importantChemical.getInchi());
            nextLine.add(mapper.writeValueAsString(importantChemical.getMetadata()));
            printer.printRecord(nextLine);
        }
        printer.flush();
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:mekhq.Utilities.java

/**
 * Export a JTable to a CSV file//from w  w  w. j a va  2  s .  c  o  m
 * @param table
 * @param file
 * @return report
 */
public static String exportTabletoCSV(JTable table, File file) {
    String report;
    try {
        TableModel model = table.getModel();
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath()));
        String[] columns = new String[model.getColumnCount()];
        for (int i = 0; i < model.getColumnCount(); i++) {
            columns[i] = model.getColumnName(i);
        }
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(columns));

        for (int i = 0; i < model.getRowCount(); i++) {
            Object[] towrite = new String[model.getColumnCount()];
            for (int j = 0; j < model.getColumnCount(); j++) {
                // use regex to remove any HTML tags
                towrite[j] = model.getValueAt(i, j).toString().replaceAll("\\<[^>]*>", "");
            }
            csvPrinter.printRecord(towrite);
        }

        csvPrinter.flush();
        csvPrinter.close();

        report = model.getRowCount() + " " + resourceMap.getString("RowsWritten.text");
    } catch (Exception ioe) {
        MekHQ.getLogger().log(Utilities.class, "exportTabletoCSV", LogLevel.INFO, "Error exporting JTable");
        report = "Error exporting JTable. See log for details.";
    }
    return report;
}

From source file:be.roots.taconic.pricingguide.service.ReportServiceImpl.java

@Override
public void report(Contact contact, List<String> modelIds) throws IOException {

    final CSVFormat csvFileFormat = CSVFormat.DEFAULT;
    final FileWriter fileWriter = new FileWriter(getFileNameFor(new DateTime()), true);
    final CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

    final List<String> record = new ArrayList<>();

    record.add(new DateTime().toString(DefaultUtil.FORMAT_TIMESTAMP));

    record.add(contact.getHsId());//from  w  w w.ja va 2s .com
    record.add(contact.getSalutation());
    record.add(contact.getFirstName());
    record.add(contact.getLastName());
    record.add(contact.getEmail());
    record.add(contact.getCompany());
    record.add(contact.getCountry());
    record.add(contact.getPersona());
    if (contact.getJobRole() != null) {
        record.add(contact.getJobRole().getDescription());
    } else {
        record.add(null);
    }
    if (contact.getCurrency() != null) {
        record.add(contact.getCurrency().name());
        record.add(contact.getCurrency().getDescription());
    } else {
        record.add(null);
        record.add(null);
    }

    record.addAll(modelIds);

    csvFilePrinter.printRecord(record);
    csvFilePrinter.close();

}

From source file:com.itemanalysis.jmetrik.file.JmetrikFileImporter.java

private void convertFile() {
    CSVParser parser = null;/*w  w w  .j av a  2 s .  c om*/
    Reader reader = null;
    CSVPrinter printer = null;
    Writer writer = null;

    try {
        if (outputFile.exists()) {
            if (!overwrite) {
                theException = new IOException("File already exists and overwrite==false");
                return;
            }
        } else {
            outputFile.createNewFile();
        }

        //For debugging
        //            System.out.println("CREATED: " + outputFile.getAbsolutePath());

        //Writer header to file
        writer = new OutputStreamWriter(new FileOutputStream(outputFile));
        printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#'));

        printer.printComment("VERSION");
        printer.printRecord(new String[] { "jmetrik1" });
        printer.printComment("METADATA");
        printer.printRecord(new String[] { Integer.valueOf(nrow).toString() });
        printer.printComment("ATTRIBUTES");
        for (VariableName v : variableAttributeMap.keySet()) {
            printer.printRecord(variableAttributeMap.get(v).getAttributeArray());
        }
        printer.printComment("DATA");

        //Write data to file
        reader = new InputStreamReader(new BOMInputStream(new FileInputStream(dataFile)), "UTF-8");
        parser = new CSVParser(reader, dataFileFormat);

        if (hasHeader) {
            parser = new CSVParser(reader, dataFileFormat.withHeader(colNames).withSkipHeaderRecord(true));
        } else {
            parser = new CSVParser(reader, dataFileFormat.withHeader(colNames));
        }

        Iterator<CSVRecord> iter = parser.iterator();
        CSVRecord csvRecord = null;
        VariableAttributes variableAttributes = null;
        DataType dataType = null;
        String temp = "";

        while (iter.hasNext()) {
            csvRecord = iter.next();

            for (VariableName v : variableAttributeMap.keySet()) {
                temp = csvRecord.get(v.toString());
                variableAttributes = variableAttributeMap.get(v);
                dataType = variableAttributes.getDataType();
                if (!variableAttributes.isMissing(temp)) {
                    if (DataType.INTEGER == dataType) {
                        printer.print(Double.valueOf(Double.parseDouble(temp)).intValue());
                    } else if (DataType.DOUBLE == dataType) {
                        printer.print(Double.parseDouble(temp));
                    } else {
                        printer.print(temp);
                    }
                } else {
                    printer.print(temp);
                }

            }
            printer.println();
        }

    } catch (IOException ex) {
        theException = ex;
    } finally {
        try {
            if (parser != null)
                parser.close();
            if (reader != null)
                reader.close();
            if (printer != null)
                printer.close();
            if (writer != null)
                writer.close();
        } catch (IOException ex) {
            theException = ex;
            logger.fatal(ex);
        }
    }
}