當前位置: 首頁>>代碼示例>>Java>>正文


Java CSVPrinter類代碼示例

本文整理匯總了Java中org.apache.commons.csv.CSVPrinter的典型用法代碼示例。如果您正苦於以下問題:Java CSVPrinter類的具體用法?Java CSVPrinter怎麽用?Java CSVPrinter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


CSVPrinter類屬於org.apache.commons.csv包,在下文中一共展示了CSVPrinter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: exportMetaDataToCSV

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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();
}
 
開發者ID:UKPLab,項目名稱:argument-reasoning-comprehension-task,代碼行數:26,代碼來源:ExportHelper.java

示例2: write

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
@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;
   }
}
 
開發者ID:frictionlessdata,項目名稱:tableschema-java,代碼行數:22,代碼來源:CsvDataSource.java

示例3: logResults

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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);
	}
}
 
開發者ID:heindorf,項目名稱:cikm16-wdvd-feature-extraction,代碼行數:26,代碼來源:ActionStatisticsProcessor.java

示例4: toCSVLine

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
@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());
}
 
開發者ID:miguel-porto,項目名稱:flora-on-server,代碼行數:24,代碼來源:TaxEntAndNativeStatusResult.java

示例5: writeVertexCSV

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
/**
 * 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());
    }
}
 
開發者ID:IBM,項目名稱:janusgraph-utils,代碼行數:28,代碼來源:CSVGenerator.java

示例6: writeVertexCSV

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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());
    }
}
 
開發者ID:tedhtchang,項目名稱:JanusGraphBench,代碼行數:23,代碼來源:CSVGenerator.java

示例7: run

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
@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());
	}

}
 
開發者ID:xabgesagtx,項目名稱:mensa-api,代碼行數:19,代碼來源:ExportLabelsJob.java

示例8: run

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
@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());
	}

}
 
開發者ID:xabgesagtx,項目名稱:mensa-api,代碼行數:19,代碼來源:ExportAllergensJob.java

示例9: run

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
@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());
	}

}
 
開發者ID:xabgesagtx,項目名稱:mensa-api,代碼行數:21,代碼來源:ExportMensasJob.java

示例10: convertScenarios

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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);
        }
    }
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:18,代碼來源:StepMap.java

示例11: saveChanges

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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);
    }
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:20,代碼來源:CSVUtils.java

示例12: save

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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);
        }
    }
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:17,代碼來源:TestCase.java

示例13: save

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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();
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:17,代碼來源:TestSet.java

示例14: processRecordY

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
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;
}
 
開發者ID:cslbehring,項目名稱:public_hdf_processors_ConvertAvroToCSV,代碼行數:21,代碼來源:CsvProcessor.java

示例15: appendCSV

import org.apache.commons.csv.CSVPrinter; //導入依賴的package包/類
/**
 * 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();
	}
}
 
開發者ID:yyang325,項目名稱:YahooFinanceTradingSystem,代碼行數:24,代碼來源:CsvUtil.java


注:本文中的org.apache.commons.csv.CSVPrinter類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。