List of usage examples for org.apache.commons.csv CSVPrinter CSVPrinter
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException
From source file:de.tudarmstadt.ukp.clarin.webanno.monitoring.page.AgreementTable.java
private InputStream generateCsvReport(AgreementResult aResult) throws UnsupportedEncodingException, IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); try (CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(buf, "UTF-8"), CSVFormat.RFC4180)) { AgreementUtils.toCSV(printer, aResult); }/* www.j a va2 s . c o m*/ return new ByteArrayInputStream(buf.toByteArray()); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step8GoldDataAggregator.java
public static File printHashMap(Map<String, Annotations> annotations, int numberOfAnnotators) { File dir = new File(TEMP_DIR); CSVPrinter csvFilePrinter;/*from www .ja v a2 s. c om*/ FileWriter fileWriter; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator('\n').withDelimiter(',').withQuote(null); File filename = null; try { filename = File.createTempFile(TEMP_CSV, EXT, dir); fileWriter = new FileWriter(filename); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); int count = 0; for (Map.Entry entry : annotations.entrySet()) { Annotations votes = (Annotations) entry.getValue(); //Create the CSVFormat object with "\n" as a record delimiter if (votes == null) { throw new IllegalStateException("There are no votes for " + entry.getKey()); } ArrayList<Integer> trueAnnotators = (ArrayList<Integer>) votes.trueAnnotations; ArrayList<Integer> falseAnnotators = (ArrayList<Integer>) votes.falseAnnotations; if (trueAnnotators.size() + falseAnnotators.size() < 5) { try { throw new IllegalStateException( "There are " + trueAnnotators.size() + " true and " + falseAnnotators.size() + " false and annotations for " + entry.getKey() + " element"); } catch (IllegalStateException ex) { ex.printStackTrace(); } } List<String> votesString = Arrays.asList(new String[numberOfAnnotators]); for (int i = 0; i < numberOfAnnotators; i++) { if (trueAnnotators.contains(i)) { votesString.set(i, "true"); } else if (falseAnnotators.contains(i)) { votesString.set(i, "false"); } else votesString.set(i, ""); } if (votesString.size() != numberOfAnnotators) { throw new IllegalStateException( "Number of annotators is " + votesString.size() + " expected " + numberOfAnnotators); } else { csvFilePrinter.printRecord(votesString); } if (count % 1000 == 0) { System.out.println("Processed " + count + " instances"); } count++; } fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (Exception e) { System.out.println("Error in CsvFileWriter !!!"); e.printStackTrace(); } System.out.println("Wrote to temporary file " + filename); return filename; }
From source file:com.team3637.service.TagServiceMySQLImpl.java
@Override public void exportCSV(String outputFile) { List<Tag> data = getTags(); FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null;/*from w w w . ja va2 s.co m*/ try { 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: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 . co m*/ * @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:dk.dma.ais.abnormal.analyzer.analysis.FreeFlowAnalysis.java
private void writeToCSVFile(FreeFlowData freeFlowData) { if (csvFileName == null) return;/*from w ww . j a v a 2s.c om*/ final File csvFile = new File(csvFileName); final boolean fileExists = csvFile.exists() == true || csvFile.length() > 0; lock.lock(); if (!fileExists) { try { if (csvFilePrinter != null) csvFilePrinter.close(); if (fileWriter != null) fileWriter.close(); } catch (IOException e) { LOG.warn(e.getMessage(), e); } csvFilePrinter = null; fileWriter = null; } try { if (fileWriter == null) { try { fileWriter = new FileWriter(csvFile, true); if (csvFilePrinter == null) { try { csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.RFC4180.withCommentMarker('#')); } catch (IOException e) { csvFilePrinter = null; LOG.error(e.getMessage(), e); LOG.error("Failed to write line to CSV file: " + freeFlowData); return; } } } catch (IOException e) { fileWriter = null; LOG.error(e.getMessage(), e); LOG.error("Failed to write line to CSV file: " + freeFlowData); return; } } if (!fileExists) { LOG.info("Created new CSV file: " + csvFile.getAbsolutePath()); csvFilePrinter.printComment("Generated by AIS Abnormal Behaviour Analyzer"); csvFilePrinter.printComment("File created: " + fmt.print(new Date().getTime())); csvFilePrinter.printRecord("TIMESTAMP (GMT)", "MMSI1", "NAME1", "TP1", "LOA1", "BM1", "COG1", "HDG1", "SOG1", "LAT1", "LON1", "MMSI2", "NAME2", "TP2", "LOA2", "BM2", "COG2", "HDG2", "SOG2", "LAT2", "LON2", "BRG", "DST"); } final Track t0 = freeFlowData.getTrackSnapshot(); final Position p0 = freeFlowData.getTrackCenterPosition(); List<FreeFlowData.TrackInsideEllipse> tracks = freeFlowData.getTracksInsideEllipse(); for (FreeFlowData.TrackInsideEllipse track : tracks) { final Track t1 = track.getTrackSnapshot(); final Position p1 = track.getTrackCenterPosition(); final int d = (int) p0.distanceTo(p1, CoordinateSystem.CARTESIAN); final int b = (int) p0.rhumbLineBearingTo(p1); List csvRecord = new ArrayList<>(); csvRecord.add(String.format(Locale.ENGLISH, "%s", fmt.print(t0.getTimeOfLastPositionReport()))); csvRecord.add(String.format(Locale.ENGLISH, "%d", t0.getMmsi())); csvRecord.add( String.format(Locale.ENGLISH, "%s", trimAisString(t0.getShipName()).replace(',', ' '))); csvRecord.add(String.format(Locale.ENGLISH, "%d", t0.getShipType())); csvRecord.add(String.format(Locale.ENGLISH, "%d", t0.getVesselLength())); csvRecord.add(String.format(Locale.ENGLISH, "%d", t0.getVesselBeam())); csvRecord.add(String.format(Locale.ENGLISH, "%.0f", t0.getCourseOverGround())); csvRecord.add(String.format(Locale.ENGLISH, "%.0f", t0.getTrueHeading())); csvRecord.add(String.format(Locale.ENGLISH, "%.0f", t0.getSpeedOverGround())); csvRecord.add(String.format(Locale.ENGLISH, "%.4f", p0.getLatitude())); csvRecord.add(String.format(Locale.ENGLISH, "%.4f", p0.getLongitude())); csvRecord.add(String.format(Locale.ENGLISH, "%d", t1.getMmsi())); csvRecord.add( String.format(Locale.ENGLISH, "%s", trimAisString(t1.getShipName()).replace(',', ' '))); csvRecord.add(String.format(Locale.ENGLISH, "%d", t1.getShipType())); csvRecord.add(String.format(Locale.ENGLISH, "%d", t1.getVesselLength())); csvRecord.add(String.format(Locale.ENGLISH, "%d", t1.getVesselBeam())); csvRecord.add(String.format(Locale.ENGLISH, "%.0f", t1.getCourseOverGround())); csvRecord.add(String.format(Locale.ENGLISH, "%.0f", t1.getTrueHeading())); csvRecord.add(String.format(Locale.ENGLISH, "%.0f", t1.getSpeedOverGround())); csvRecord.add(String.format(Locale.ENGLISH, "%.4f", p1.getLatitude())); csvRecord.add(String.format(Locale.ENGLISH, "%.4f", p1.getLongitude())); csvRecord.add(String.format(Locale.ENGLISH, "%d", b)); csvRecord.add(String.format(Locale.ENGLISH, "%d", d)); try { csvFilePrinter.printRecord(csvRecord); } catch (IOException e) { LOG.error(e.getMessage(), e); LOG.error("Failed to write line to CSV file: " + freeFlowData); } } csvFilePrinter.flush(); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { lock.unlock(); } }
From source file:com.siemens.sw360.portal.portlets.admin.ComponentUploadPortlet.java
@NotNull private ByteArrayOutputStream writeCsvStream(List<List<String>> listList) throws TException, IOException { final ByteArrayOutputStream riskCategoryCsvStream = new ByteArrayOutputStream(); Writer out = new BufferedWriter(new OutputStreamWriter(riskCategoryCsvStream)); CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat); csvPrinter.printRecords(listList);/*from www. j a v a 2 s .co m*/ csvPrinter.flush(); csvPrinter.close(); return riskCategoryCsvStream; }
From source file:com.streamsets.pipeline.kafka.common.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;/*from w w w .ja v a2s.co m*/ 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; }
From source file:com.ibm.watson.developer_cloud.professor_languo.model.stack_exchange.CorpusBuilder.java
/** * get the csv printer if it has been created , create a new one if the csv printer doesn't exist. * The reason of doing so is to allow multiple duplicate threads to be serialized to the same TSV * file without overwriting each other/*from w ww. ja va 2 s.c o m*/ * * @param tsvDir - the folder containing the TSV file * @return the csv printer used to write to the TSV file * @throws IngestionException */ public CSVPrinter getCsvPrinter(String tsvDir) throws IngestionException { if (csvPrinter == null) { try { String tsvFilePath = tsvDir + StackExchangeConstants.DUP_THREAD_TSV_FILE_NAME + StackExchangeConstants.DUP_THREAD_TSV_FILE_EXTENSION; File csvFile = new File(tsvFilePath); if (csvFile.getParentFile() != null) csvFile.getParentFile().mkdirs(); if (!csvFile.exists()) csvFile.createNewFile(); PrintWriter writer = new PrintWriter(new FileWriter(tsvFilePath, true)); csvPrinter = new CSVPrinter(writer, CSVFormat.TDF.withHeader(getTsvColumnHeaders())); } catch (IOException e) { throw new IngestionException(e); } return csvPrinter; } return csvPrinter; }
From source file:mekhq.campaign.finances.Finances.java
public String exportFinances(String path, String format) { String report;/*from w ww . j a va 2 s . c o m*/ try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(path)); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Date", "Category", "Description", "Amount", "RunningTotal")); SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"); int running_total = 0; for (int i = 0; i < transactions.size(); i++) { running_total += transactions.get(i).getAmount(); csvPrinter.printRecord(df.format(transactions.get(i).getDate()), transactions.get(i).getCategoryName(), transactions.get(i).getDescription(), transactions.get(i).getAmount(), running_total); } csvPrinter.flush(); csvPrinter.close(); report = transactions.size() + " " + resourceMap.getString("FinanceExport.text"); } catch (IOException ioe) { MekHQ.getLogger().log(getClass(), "exportFinances", LogLevel.INFO, "Error exporting finances to " + format); report = "Error exporting finances. See log for details."; } return report; }
From source file:com.streamsets.pipeline.kafka.common.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;// ww w. j a v a2s .c o m 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; }