Java 类org.apache.commons.csv.CSVPrinter 实例源码

项目:argument-reasoning-comprehension-task    文件:ExportHelper.java   
public static String exportMetaDataToCSV(List<StandaloneArgument> arguments)
        throws IOException
{
    StringWriter sw = new StringWriter();
    CSVPrinter csvPrinter = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(
            "id", "author", "annotatedStance", "timestamp", "debateMetaData.title",
            "debateMetaData.description", "debateMetaData.url"
    ));

    for (StandaloneArgument argument : arguments) {
        csvPrinter.printRecord(
                argument.getId(),
                argument.getAuthor(),
                argument.getAnnotatedStance(),
                argument.getTimestamp(),
                argument.getDebateMetaData().getTitle(),
                argument.getDebateMetaData().getDescription(),
                argument.getDebateMetaData().getUrl()
        );
    }

    sw.flush();

    return sw.toString();
}
项目:flora-on-server    文件:TaxEntAndNativeStatusResult.java   
@Override
public void toCSVLine(CSVPrinter rec, Object obj) throws IOException {
    if(this.taxent == null) {
        rec.print("");
        return;
    }
    Map<String,InferredStatus> tStatus = this.inferNativeStatus();
    @SuppressWarnings("unchecked")
    List<String> allTerritories=(List<String>) obj;
    rec.print(this.taxent.getCurrent() ? "yes" : "no");
    rec.print(this.taxent.getID());
    rec.print((this.isLeaf ==null ? "" : (this.isLeaf ? "" : "+")) + this.taxent.getNameWithAnnotationOnly(false));
    rec.print(this.taxent.getAuthor());
    if(this.territories==null) return;

    for(String t : allTerritories) {
        if(tStatus.containsKey(t))
            rec.print(tStatus.get(t).getStatusSummary());
        else
            rec.print("");
    }
    rec.print(this.taxent.getComment());
}
项目:tableschema-java    文件:CsvDataSource.java   
@Override
public void write(String outputFilePath) throws Exception{            
   try(Writer out = new BufferedWriter(new FileWriter(outputFilePath));
           CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.RFC4180)) {

        if(this.getHeaders() != null){
            csvPrinter.printRecord(this.getHeaders());
        }

        Iterator<CSVRecord> recordIter = this.getCSVParser().iterator();
        while(recordIter.hasNext()){
            CSVRecord record = recordIter.next();
            csvPrinter.printRecord(record);
        }

        csvPrinter.flush();

   }catch(Exception e){
        throw e;
   }
}
项目:janusgraph-utils    文件:CSVGenerator.java   
/**
 * Create csv files for a VertexType
 * @param type a vertex type
 * @param outputDirectory the output folder to write the csv file
 */
void writeVertexCSV(VertexTypeBean type, String outputDirectory ){
    String csvFile = outputDirectory + "/" + type.name + ".csv";
    ArrayList<String> header = new ArrayList<String>();
    header.add("node_id");
    header.addAll(type.columns.keySet());
    int botId = idFactory.getMinId(type.name);
    int topId = idFactory.getMaxId(type.name);
    try {
        CSVPrinter csvFilePrinter = new CSVPrinter(new FileWriter(csvFile), csvFileFormat);
        csvFilePrinter.printRecord(header);
        for (int i = botId; i<=topId; i++){
            ArrayList<Object> record = new ArrayList<Object>();
            record.add(i);
            record.addAll(generateOneRecord(type.columns));
            csvFilePrinter.printRecord(record);
        }
        csvFilePrinter.close();
        System.out.println("Generated vertex file: "+ csvFile);
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}
项目:JanusGraphBench    文件:CSVGenerator.java   
void writeVertexCSV(VertexTypeBean type, String outputDirectory ){
    String csvFile = outputDirectory + "/" + type.name + ".csv";
    ArrayList<String> header = new ArrayList<String>();
    header.add("node_id");
    header.addAll(type.columns.keySet());
    int botId = idFactory.getMinId(type.name);
    int topId = idFactory.getMaxId(type.name);
    try {
        CSVPrinter csvFilePrinter = new CSVPrinter(new FileWriter(csvFile), csvFileFormat);
        csvFilePrinter.printRecord(header);
        for (int i = botId; i<=topId; i++){
            ArrayList<Object> record = new ArrayList<Object>();
            record.add(i);
            record.addAll(generateOneRecord(type.columns));
            csvFilePrinter.printRecord(record);
        }
        csvFilePrinter.close();
        System.out.println("Generated vertex file: "+ csvFile);
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}
项目:mensa-api    文件:ExportLabelsJob.java   
@Override
public void run() {
    log.info("Start exporting labels");
    List<Label> labels = repo.findAllByOrderByName();
    File outputFile = exportDirPath.resolve("labels.csv").toFile();
    CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("name", "imageUrl").withRecordSeparator('\n');
    try (FileWriter writer = new FileWriter(outputFile);
         CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)
    ) {
        for (Label label : labels) {
            csvPrinter.printRecord(label.getName(), label.getImageUrl());
        }
        log.info("Finished exporting {} labels to file {}", labels.size(), outputFile);
    } catch (IOException e) {
        log.error("Failed to export labels to file {} due to error: {}", outputFile.getAbsolutePath(), e.getMessage());
    }

}
项目:mensa-api    文件:ExportAllergensJob.java   
@Override
public void run() {
    log.info("Start exporting allergens");
    List<Allergen> allergens = repo.findAllByOrderByNumberAsc();
    File outputFile = exportDirPath.resolve("allergens.csv").toFile();
    CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("number", "name").withRecordSeparator('\n');
    try (FileWriter writer = new FileWriter(outputFile);
         CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)
    ) {
        for (Allergen allergen : allergens) {
            csvPrinter.printRecord(allergen.getNumber(), allergen.getName());
        }
        log.info("Finished exporting {} allergens to file {}", allergens.size(), outputFile);
    } catch (IOException e) {
        log.error("Failed to export allergens to file {} due to error: {}", outputFile.getAbsolutePath(), e.getMessage());
    }

}
项目:mensa-api    文件:ExportMensasJob.java   
@Override
public void run() {
    log.info("Start exporting mensas");
    List<Mensa> mensas = repo.findAllByOrderByName();
    File outputFile = exportDirPath.resolve("mensas.csv").toFile();
    CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("id", "mainUrl", "name", "nextWeekUrl", "thisWeekUrl", "todayUrl", "tomorrowUrl", "longitude", "latitude", "address", "zipcode", "city").withRecordSeparator('\n');
    try (FileWriter writer = new FileWriter(outputFile);
         CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)
    ) {
        for (Mensa mensa : mensas) {
            String longitude = mensa.getPoint() == null ? StringUtils.EMPTY : Double.toString(mensa.getPoint().getX());
            String latitude = mensa.getPoint() == null ? StringUtils.EMPTY : Double.toString(mensa.getPoint().getY());
            csvPrinter.printRecord(mensa.getId(), mensa.getMainUrl(), mensa.getName(), mensa.getNextWeekUrl(), mensa.getThisWeekUrl(), mensa.getTodayUrl(), mensa.getTomorrowUrl(), longitude, latitude, mensa.getAddress(), mensa.getZipcode(), mensa.getCity());
        }
        log.info("Finished exporting {} mensas to file {}", mensas.size(), outputFile);
    } catch (IOException e) {
        log.error("Failed to export mensas to file {} due to error: {}", outputFile.getAbsolutePath(), e.getMessage());
    }

}
项目:Cognizant-Intelligent-Test-Scripter    文件:StepMap.java   
public void convertScenarios(File file, List<Scenario> scenarios) {
    if (scenarios != null && !scenarios.isEmpty()) {
        try (FileWriter out = new FileWriter(file);
                CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withIgnoreEmptyLines());) {
            printer.printRecord(HEADERS);
            for (Scenario scenario : scenarios) {
                for (TestCase testCase : scenario.getTestCases()) {
                    convertTestCase(testCase, printer);
                    printer.println();
                }
                printer.println();
            }
        } catch (Exception ex) {
            Logger.getLogger(StepMap.class.getName()).log(Level.SEVERE, "Error while converting", ex);
        }
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CSVUtils.java   
public static void saveChanges(GlobalDataModel globalData) {
    createIfNotExists(globalData.getLocation());
    try (FileWriter out = new FileWriter(new File(globalData.getLocation()));
            CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withIgnoreEmptyLines());) {
        for (String header : globalData.getColumns()) {
            printer.print(header);
        }
        printer.println();
        globalData.removeEmptyRecords();
        for (List<String> record : globalData.getRecords()) {
            for (String value : record) {
                printer.print(value);
            }
            printer.println();
        }
    } catch (Exception ex) {
        Logger.getLogger(CSVUtils.class.getName()).log(Level.SEVERE, "Error while saving", ex);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:CSVUtils.java   
public static void saveChanges(TestDataModel testData) {
    createIfNotExists(testData.getLocation());
    try (FileWriter out = new FileWriter(new File(testData.getLocation()));
            CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withIgnoreEmptyLines());) {
        for (String header : testData.getColumns()) {
            printer.print(header);
        }
        printer.println();
        testData.removeEmptyRecords();
        for (Record record : testData.getRecords()) {
            for (String value : record) {
                printer.print(value);
            }
            printer.println();
        }
    } catch (Exception ex) {
        Logger.getLogger(CSVUtils.class.getName()).log(Level.SEVERE, "Error while saving", ex);
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:TestCase.java   
public void save() {
    if (!isSaved()) {
        createIfNotExists();
        try (FileWriter out = new FileWriter(new File(getLocation())); CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withIgnoreEmptyLines());) {
            printer.printRecord(HEADERS.getValues());
            removeEmptySteps();
            autoNumber();
            for (TestStep testStep : testSteps) {
                printer.printRecord(testStep.stepDetails);
            }
            setSaved(true);
        } catch (Exception ex) {
            Logger.getLogger(TestCase.class.getName()).log(Level.SEVERE, "Error while saving", ex);
        }
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:TestSet.java   
public void save() {
    if (!isSaved()) {
        createIfNotExists();
        try (FileWriter out = new FileWriter(new File(getLocation())); CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withIgnoreEmptyLines());) {
            printer.printRecord(HEADERS.getValues());
            removeEmptySteps();
            for (ExecutionStep testStep : testSteps) {
                printer.printRecord(testStep.exeStepDetails);
            }
            setSaved(true);
        } catch (Exception ex) {
            Logger.getLogger(TestSet.class.getName()).log(Level.SEVERE, "Error while saving", ex);
        }
    }
    execSettings.save();
}
项目:public_hdf_processors_ConvertAvroToCSV    文件:CsvProcessor.java   
public static List processRecordY(CSVPrinter printer, GenericRecord record, List<Column> columns)
        throws IOException {
    List r = new ArrayList<>();
    columns.forEach(c -> {
        try {
            r.add(record.get(c.getField().name()));
        } catch (Exception e) {

            try {
                r.add(c.getDefaultValue());
            } catch (Exception e2) {
                r.add("NULL");
            }
        }
    });

    printer.printRecord(r);
    printer.flush();
    return r;
}
项目:YahooFinanceTradingSystem    文件:CsvUtil.java   
/**
 * this method is used to append pending transactions to the csv file
 * @param trans
 */
public void appendCSV(UserStockTransaction trans){
    try{

        filePath = servletContext.getRealPath("WEB-INF/csv/pending.csv");
        File f = new File(filePath);
        //System.out.println(trans.getStock().getSymbol() + " " + trans.getUser().getUsername() + " " + trans.getPrice());

        FileWriter fw = new FileWriter(f, true);            
        CSVPrinter cp = new CSVPrinter(fw, CSVFormat.DEFAULT);
        System.out.println("Appending a transaction");
        System.out.println(trans.toString());
        cp.printRecord((Object[]) trans.toString().split(","));
        fw.flush();
        fw.close();
        cp.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}
项目:YahooFinanceTradingSystem    文件:CsvUtil.java   
/**
 * this method is used to rewrite the csv file for all the pending transactions
 * @param trans
 */
public void rewriteCSV(List<UserStockTransaction> trans){
    try{

        filePath = servletContext.getRealPath("WEB-INF/csv/pending.csv");
        File f = new File(filePath);

        FileWriter fw = new FileWriter(f);          
        CSVPrinter cp = new CSVPrinter(fw, CSVFormat.DEFAULT);
        System.out.println(trans.toString());
        for(UserStockTransaction tx: trans){
            cp.printRecord((Object[]) tx.toString().split(","));
        }
        fw.flush();
        fw.close();
        cp.close();         
    }catch (Exception e){
        e.printStackTrace();
    }
}
项目:cikm16-wdvd-feature-extraction    文件:ActionStatisticsProcessor.java   
private void logResults() {
    logger.info("Action frequency distribution:\n" + FrequencyUtils.formatFrequency(actionDistribution));
    logger.info("Action frequency distribution of rollback-reverted revisions:\n" + FrequencyUtils.formatFrequency(rollbackRevertedActionDistribution));
    logger.info("Action frequency distribution of non-rollback-reverted revisions:\n" + FrequencyUtils.formatFrequency(nonRollbackRevertedActionDistribution));

    try {
        Writer writer = new PrintWriter(path, "UTF-8");
        CSVPrinter csvWriter = CSVFormat.RFC4180.withQuoteMode(QuoteMode.ALL)
                .withHeader("month", "action", "count").print(writer);

        for (Entry<String, HashMap<String, Integer>> entry: getSortedList(monthlyActionDistribution)) {
            String month = entry.getKey();

            for (Entry<String, Integer> entry2: getSortedList2(entry.getValue())) {
                String action = entry2.getKey();
                Integer value = entry2.getValue();

                csvWriter.printRecord(month, action, value);
            }
        }
        csvWriter.close();
    } catch (IOException e) {
        logger.error("", e);
    }
}
项目:o3smeasures-tool    文件:FileExport.java   
/**
 * Method to create a csv file with the measurement result.
 * @author Mariana Azevedo
 * @since 13/07/2014
 * @param outputFile
 * @param item
 * @throws IOException 
 */
public void createCSVFile(String outputFile, ItemMeasured item) throws IOException{

    setFolderPath();        
    populateHeader();

    File file = new File(tempFolderPath + outputFile + ".csv");
    if (!file.exists()){
        boolean isFileCreated = file.createNewFile();
        logger.info("File created " + isFileCreated);
    }

    try (FileWriter fileWriter = new FileWriter(file, true);
         CSVPrinter csvOutput = new CSVPrinter(fileWriter, CSVFormat.DEFAULT)) {

        csvOutput.printRecords(headerItems);
        List<String[]> it = populateItems(item);
        csvOutput.printRecords(it);

        JOptionPane.showMessageDialog(null, "CSV file was created successfully!");

    }catch (IOException exception) {
        JOptionPane.showMessageDialog(null, "Error in CsvFileWriter!");
        logger.error(exception);
    } 
}
项目:sociallink    文件:RobustTsvOutputFormat.java   
@Override
public void open(int taskNumber, int numTasks) throws IOException {
    super.open(taskNumber, numTasks);
    OutputStream outputStream;
    if (this.enableGzip) {
        outputStream = new GZIPOutputStream(this.stream, 4096, false);
    } else {
        outputStream = new BufferedOutputStream(this.stream, 4096);
    }
    this.wrt = new CSVPrinter(new OutputStreamWriter(outputStream), FORMAT);

    String nullCounterName = sanitizePathName(outputFilePath);
    if (nullCounterName.charAt(0) != '-') {
        nullCounterName = "-"+nullCounterName;
    }
    nullCounterName = "null-counter"+nullCounterName;

    getRuntimeContext().addAccumulator(nullCounterName, this.nullCounter);
}
项目:thingsboard    文件:CassandraDbHelper.java   
public static Path dumpCfIfExists(KeyspaceMetadata ks, Session session, String cfName,
                                  String[] columns, String[] defaultValues, String dumpPrefix) throws Exception {
    if (ks.getTable(cfName) != null) {
        Path dumpFile = Files.createTempFile(dumpPrefix, null);
        Files.deleteIfExists(dumpFile);
        try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(dumpFile), CSV_DUMP_FORMAT)) {
            Statement stmt = new SimpleStatement("SELECT * FROM " + cfName);
            stmt.setFetchSize(1000);
            ResultSet rs = session.execute(stmt);
            Iterator<Row> iter = rs.iterator();
            while (iter.hasNext()) {
                Row row = iter.next();
                if (row != null) {
                    dumpRow(row, columns, defaultValues, csvPrinter);
                }
            }
        }
        return dumpFile;
    } else {
        return null;
    }
}
项目:thingsboard    文件:CassandraDbHelper.java   
public static void appendToEndOfLine(Path targetDumpFile, String toAppend) throws Exception {
    Path tmp = Files.createTempFile(null, null);
    try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(targetDumpFile), CSV_DUMP_FORMAT)) {
        try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(tmp), CSV_DUMP_FORMAT)) {
            csvParser.forEach(record -> {
                List<String> newRecord = new ArrayList<>();
                record.forEach(val -> newRecord.add(val));
                newRecord.add(toAppend);
                try {
                    csvPrinter.printRecord(newRecord);
                } catch (IOException e) {
                    throw new RuntimeException("Error appending to EOL", e);
                }
            });
        }
    }
    Files.move(tmp, targetDumpFile, StandardCopyOption.REPLACE_EXISTING);
}
项目:process-monitor    文件:CsvOutputComparator.java   
private void printRecord(CSVPrinter csv, String version, String fileName, CSVRecord record) throws IOException {
    List<Object> values = new ArrayList<>();

    values.add(version);
    values.add(fileName);
    for (Measure measure : Measure.values()) {
        values.add(record.get(measure.columnMin()));
        values.add(record.get(measure.columnMax()));
        values.add(record.get(measure.columnMean()));
        values.add(record.get(measure.columnStandardDeviation()));
        values.add(record.get(measure.columnMedian()));
        values.add(record.get(measure.column75Percentile()));
    }

    csv.printRecord(values);
}
项目:TundraCSV.java    文件:IDataCSVParser.java   
/**
 * Returns a CSV representation of the given IData object.
 *
 * @param document  The IData to convert to CSV.
 * @return          The CSV representation of the IData.
 */
@Override
public String encodeToString(IData document) throws IOException {
    if (document == null) return null;

    IDataCursor cursor = document.getCursor();
    IData[] records = IDataUtil.getIDataArray(cursor, "recordWithNoID");
    cursor.destroy();

    if (records == null) return null;
    if (records.length == 0) return "";

    String[] columns = this.columns;
    if (columns == null || columns.length == 0) columns = IDataHelper.getKeys(records);

    StringBuilder builder = new StringBuilder();
    CSVPrinter printer = new CSVPrinter(builder, formatter(columns));

    for (IData record : records) {
        if (record != null) printer.printRecord(IDataHelper.getValues(record));
    }

    return builder.toString();
}
项目:perfcharts    文件:ZabbixParser.java   
private static void parseCPULoad(ZabbixItem item,
        Map<Integer, List<ZabbixHistory>> itemID2History,
        CSVPrinter csvPrinter) throws IOException {
    Matcher m = optionsPattern.matcher(item.getKey());
    String label = "CPULOAD_1MIN";
    if (m.find()) {
        String option = m.group();
        // if (option.contains("percpu")) {
        // LOGGER.warning("Zabbix item key \""
        // + item.getKey()
        // +
        // "\" is ignored bacause its arguments are incompatible with this program.");
        // return;
        // }
        if (option.contains("avg5")) {
            label = "CPULOAD_5MIN";
        } else if (option.contains("avg15")) {
            label = "CPULOAD_15MIN";
        }
    }
    LOGGER.info("Parsing Zabbix item key \"" + item.getKey() + "...");
    writeHistory(label, itemID2History.get(item.getItemID()), csvPrinter);
}
项目:fim    文件:DuplicateOutputGenerator.java   
private void generateCSV(List<DuplicatedFiles> duplicates) {
    CSVFormat format = CSVFormat.DEFAULT.withHeader("SetIndex", "FileIndex", "WastedSpace", "FilePath", "FileName", "FileLength", "FileType");
    try (CSVPrinter csvPrinter = new CSVPrinter(Logger.out, format)) {
        int setIndex = 0;
        for (DuplicatedFiles files : duplicates) {
            setIndex++;
            int fileIndex = 0;
            for (DuplicatedFile file : files.getFileList()) {
                fileIndex++;
                csvPrinter.printRecord(setIndex, fileIndex, files.getWastedSpace(), file.getPath(), file.getName(), file.getLength(), file.getType());
            }
        }
        csvPrinter.flush();
    } catch (IOException ex) {
        Logger.error("Error displaying duplicates in CSV format", ex, context.isDisplayStackTrace());
    }
}
项目:vetaraus    文件:CSV.java   
/**
 * Write a given list of Case objects with a given CSV-delimiter to any Appendable output (i.e. printer).
 * <p>
 * The output file will include a header record and print the following values:
 * ID, age, gender, married, children, degree, occupation, income, tariff.
 *
 * @param cases
 *         The list of Case objects to write
 * @param delimiter
 *         The delimiter between each CSV column.
 * @param out
 *         The Appendable output to which the data should be written.
 * @throws IOException
 */
public static void write(List<Case> cases, Character delimiter, Appendable out) throws IOException {
    try (CSVPrinter writer = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(delimiter))) {
        // print headers
        writer.printRecord(Constants.HEADER_NUMBER, Constants.HEADER_AGE, Constants.HEADER_GENDER, Constants.HEADER_MARRIED,
                Constants.HEADER_CHILDREN, Constants.HEADER_DEGREE, Constants.HEADER_OCCUPATION, Constants.HEADER_INCOME, Constants.HEADER_TARIFF);
        for (Case c : cases) {
            writer.printRecord(c.getNumber(),
                    c.getAge(),
                    c.getGender(),
                    c.getMarried(),
                    c.getChildCount(),
                    c.getDegree(),
                    c.getOccupation(),
                    c.getIncome(),
                    c.getTariff()
            );
        }
        writer.flush();
    }
}
项目:webanno    文件:AgreementUtils.java   
private static void configurationSetsWithItemsToCsv(CSVPrinter aOut,
        AgreementResult aAgreement, List<ConfigurationSet> aSets)
    throws IOException
{
    List<String> headers = new ArrayList<>(
            asList("Type", "Collection", "Document", "Layer", "Feature", "Position"));
    headers.addAll(aAgreement.getCasGroupIds());
    aOut.printRecord(headers);

    int i = 0;
    for (ICodingAnnotationItem item : aAgreement.getStudy().getItems()) {
        Position pos = aSets.get(i).getPosition();
        List<String> values = new ArrayList<>();
        values.add(pos.getClass().getSimpleName());
        values.add(pos.getCollectionId());
        values.add(pos.getDocumentId());
        values.add(pos.getType());
        values.add(aAgreement.getFeature());
        values.add(aSets.get(i).getPosition().toMinimalString());
        for (IAnnotationUnit unit : item.getUnits()) {
            values.add(String.valueOf(unit.getCategory()));
        }
        aOut.printRecord(values);
        i++;
    }
}
项目:fusion-client-tools    文件:FusionPipelineClient.java   
public void writeTo(OutputStream outputStream) throws IOException {
  try (OutputStreamWriter osw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
    CSVPrinter csvPrinter = new CSVPrinter(osw, CSVFormat.DEFAULT);
    for (Object doc : docs) {
      if (doc instanceof Map) {
        Map<String,Object> map = (Map<String,Object>)doc;
        csvPrinter.printRecord(map.values());
      } else {
        csvPrinter.print(doc);
        csvPrinter.println();
      }
    }
    csvPrinter.flush();
    csvPrinter.close();
  }
}
项目:teambuilder    文件:CsvLoader.java   
private void saveActivities(Repository repo) throws IOException {
    final Appendable out = new FileWriter(getActivitiesFilename());
    final CSVPrinter printer = CSVFormat.EXCEL.withHeader("id", "date", "time", "title", "type", "level", "synced").print(out);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    for (Activity game : repo.getActivities()) {
        List<String> rec = new ArrayList<>();
        rec.add(game.id);
        rec.add(formatter.format(game.date));
        rec.add(game.time);
        rec.add(game.title);
        rec.add(game.type.toString());
        if (game.level != null)
            rec.add(game.level.toString());
        else
            rec.add("");
        rec.add(Boolean.toString(game.synced));
        printer.printRecord(rec);
    }
    printer.close();
}
项目:canvas-data-tools    文件:RequestAnalysis.java   
private void writeUserIps(final Path dir, final TableFormat tableFormat) throws IOException {
  final Path totalFile = dir.resolve("ipCountPerUser" + tableFormat.getExtension());
  final Path detailFile = dir.resolve("ipsPerUser" + tableFormat.getExtension());
  try (OutputStream totalOut = tableFormat.getOutputStream(totalFile);
      OutputStream detailOut = tableFormat.getOutputStream(detailFile);
      CSVPrinter totalPrinter = new CSVPrinter(new OutputStreamWriter(totalOut), tableFormat.getCsvFormat());
      CSVPrinter detailPrinter = new CSVPrinter(new OutputStreamWriter(detailOut), tableFormat.getCsvFormat())) {
    for (final Long user : userIps.keySet()) {
      final Histogram<String> ips = userIps.get(user);
      totalPrinter.printRecord(user, ips.size());
      for (final String ip : ips.keySet()) {
        detailPrinter.printRecord(user, ip, ips.get(ip));
      }
    }
  }
}
项目:flora-on-server    文件:ChecklistEntry.java   
@Override
    public void toCSVLine(CSVPrinter rec, Object obj) throws IOException {
        TaxonomicPath taxonomicPath;
        taxonomicPath = new TaxonomicPath(this.higherTaxonomy);

        if (this.taxent == null) {
            rec.print("");
            return;
        }
//        rec.print(taxonomicPath.toString());
        TaxEnt tmp;
        for(Constants.TaxonRanks cf : Constants.CHECKLISTFIELDS) {
            if((tmp = taxonomicPath.getTaxonOfRank(cf)) == null)
                rec.print("");
            else
                rec.print(tmp.getFullName(false));
        }
        super.toCSVLine(rec, obj);
    }
项目:iris    文件:StaticAddressCsvService.java   
public InputStream generateCsvReport(List<StaticAddressErrorRecord> records) {

        LOG.debug("Generating csv report with {} error records", records.size());

        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try(CSVPrinter csvPrinter = createCsvPrinter(stream)) {
            csvPrinter.printRecord(POSTAL_CODE, CITY, COUNTRY, ERROR);

            for (StaticAddressErrorRecord r : records) {
                csvPrinter.printRecord(r.getPostalCode(), r.getCity(), r.getCountry(), r.getError());
            }
        } catch (IOException e) {
            throw new StaticAddressCsvException("Error while attempting to generate csv report", e);
        }

        return new ByteArrayInputStream(stream.toByteArray());
    }
项目:iris    文件:RouteDataRevisionCsvService.java   
InputStream generateCsvReport(List<RouteDataRevisionCleanupRecord> records) {

        LOG.debug("Generating csv report with {} obsolete records", records.size());

        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try(CSVPrinter csvPrinter = createCsvPrinter(stream)) {
            csvPrinter.printRecord(ID, TERMINAL, POSTAL_CODE, CITY, COUNTRY, REVISION_TRUCK, REVISION_TOLL,
                CURRENT_TRUCK, CURRENT_TOLL, COMMENT);

            for (RouteDataRevisionCleanupRecord r : records) {
                csvPrinter.printRecord(r.getId(), r.getTerminal(), r.getPostalCode(), r.getCity(), r.getCountry(),
                    r.getRevisionTruckDistance(), r.getRevisionTollDistance(), r.getCurrentTruckDistance(),
                    r.getCurrentTollDistance(), r.getComment());
            }
        } catch (IOException e) {
            throw new RouteDataRevisionCsvException("Csv could not be generated", e);
        }

        return new ByteArrayInputStream(stream.toByteArray());
    }
项目:datacollector    文件:SdcKafkaTestUtil.java   
public List<KeyedMessage<String, String>> produceCsvMessages(String topic, String partition,
                                                                    CSVFormat csvFormat, File csvFile) throws IOException {
  List<KeyedMessage<String, String>> messages = new ArrayList<>();
  String line;
  BufferedReader bufferedReader = new BufferedReader(new FileReader(KafkaTestUtil.class.getClassLoader()
    .getResource("testKafkaTarget.csv").getFile()));
  while ((line = bufferedReader.readLine()) != null) {
    String[] strings = line.split(",");
    StringWriter stringWriter = new StringWriter();
    CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
    csvPrinter.printRecord(strings);
    csvPrinter.flush();
    csvPrinter.close();
    messages.add(new KeyedMessage<>(topic, partition, stringWriter.toString()));
  }
  return messages;
}
项目:datacollector    文件:KafkaTestUtil.java   
public static List<KeyedMessage<String, String>> produceCsvMessages(String topic, String partition,
                                                                    CSVFormat csvFormat, File csvFile) throws IOException {
  List<KeyedMessage<String, String>> messages = new ArrayList<>();
  String line;
  BufferedReader bufferedReader = new BufferedReader(new FileReader(KafkaTestUtil.class.getClassLoader()
    .getResource("testKafkaTarget.csv").getFile()));
  while ((line = bufferedReader.readLine()) != null) {
    String[] strings = line.split(",");
    StringWriter stringWriter = new StringWriter();
    CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
    csvPrinter.printRecord(strings);
    csvPrinter.flush();
    csvPrinter.close();
    messages.add(new KeyedMessage<>(topic, partition, stringWriter.toString()));
  }
  return messages;
}
项目:taxcalculator    文件:TestCreateHelper.java   
@Ignore("for conversion only")
@Test
public final void toTable() throws IOException, ParseException {
    final int size = 7;
    int no = 0;
    try (final InputStreamReader in = new InputStreamReader(
            getClass().getResourceAsStream("/info/kuechler/bmf/taxcalculator/toconvert.csv"),
            StandardCharsets.UTF_8);
            final CSVParser parser = new CSVParser(in, FORMAT);
            final CSVPrinter print = new CSVPrinter(System.out, FORMAT);) {
        for (final CSVRecord record : parser) {
            for (final String value : record) {
                print.print(convert(value));
                if (++no % size == 0) {
                    print.println();
                }
            }
        }
    }
    Assert.assertTrue(no > 0);
}
项目:mathosphere    文件:Util.java   
public static void writeExtractedDefinitionsAsCsv(String file, String qId, String title, List<Relation> relations) throws IOException {
  if (file != null) {
    final File output = new File(file);
    if (!output.exists())
      output.createNewFile();
    OutputStreamWriter w = new FileWriter(output, true);
    CSVPrinter printer = CSVFormat.DEFAULT.withRecordSeparator("\n").print(w);
    for (Relation relation : relations) {
      //qId, title, identifier, definition
      String[] out = new String[]{
        qId,
        title,
        relation.getIdentifier(),
        relation.getDefinition(), "Word number: " + String.valueOf(relation.getIdentifierPosition()),
        "\"" + "\"",
        getHumanReadableSentence(relation)};
      printer.printRecord(out);
    }
    w.flush();
    w.close();
  }
}
项目:mathosphere    文件:ConverterPairCSVToMatrix.java   
private static void writeOrderedMatrix(HashMap<Tuple2<String, String>, Double> matrix, String filepath, List<String> orderedRowValues, List<String> orderedColValues) throws Exception {
    // print to disk
    final CSVPrinter printer = new CSVPrinter(new FileWriter(filepath), CSV_FORMAT);

    // write first row (header)
    List<String> tmpHeader = new ArrayList<>();
    tmpHeader.add("");
    tmpHeader.addAll(orderedColValues);
    printer.printRecord(tmpHeader);

    System.out.println("writing " + orderedRowValues.size() + " records");
    for (String rowName : orderedRowValues) {
        printer.printRecord(
                getRowWithDescriptionInFirstCol(
                        rowName,
                        getOrderedRow(matrix, orderedColValues, rowName)));
    }
    printer.close();
}
项目:tri    文件:OccSearchGUI.java   
private void fileExportAllMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileExportAllMenuActionPerformed
    if (occurrences != null && occurrences.size() > 0) {
        if (saveFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = saveFileChooser.getSelectedFile();
            try {
                Appendable out = new FileWriter(file);
                CSVPrinter printer = CSVFormat.EXCEL.withHeader("year", "word", "score").withDelimiter('\t').print(out);
                List<Integer> years = new ArrayList<>(occurrences.keySet());
                Collections.sort(years);
                for (Integer year : years) {
                    List<Word> list = occurrences.get(year);
                    for (Word word : list) {
                        printer.printRecord(year, word.getWord(), word.getScore());
                    }
                }
                printer.close();
            } catch (IOException ex) {
                Logger.getLogger(OccSearchGUI.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
项目:tri    文件:OccSearchGUI.java   
private void fileExportMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileExportMenuActionPerformed
    Object selectedItem = comboYearResult.getSelectedItem();
    if (selectedItem != null) {
        if (saveFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = saveFileChooser.getSelectedFile();
            try {
                Appendable out = new FileWriter(file);
                CSVPrinter printer = CSVFormat.EXCEL.withHeader("year", "word", "score").withDelimiter('\t').print(out);
                List<Word> list = occurrences.get((Integer) selectedItem);
                for (Word word : list) {
                    printer.printRecord((Integer) selectedItem, word.getWord(), word.getScore());
                }
                printer.close();
            } catch (IOException ex) {
                Logger.getLogger(OccSearchGUI.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}