@Override public byte[] serialize(final String topic, final GenericRow genericRow) { if (genericRow == null) { return null; } try { final StringWriter stringWriter = new StringWriter(); final CSVPrinter csvPrinter = new CSVPrinter(stringWriter, CSVFormat.DEFAULT); csvPrinter.printRecord(genericRow.getColumns()); final String result = stringWriter.toString(); return result.substring(0, result.length() - 2).getBytes(StandardCharsets.UTF_8); } catch (final Exception e) { throw new SerializationException("Error serializing CSV message", e); } }
@Override public ByteBuffer write(List<Object> data, ByteBuffer buffer) { try { StringWriter writer = new StringWriter(); CSVPrinter printer = new CSVPrinter(writer, CSVFormat.RFC4180); for (Object o : data) { printer.print(o); } //since using StringWriter, we do not need to close it. return ByteBuffer.wrap(writer.getBuffer().toString().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } }
private static String doJoinDelimited(Iterable<?> elements, CSVFormat format) { StringWriter out = new StringWriter(); try (CSVPrinter printer = new CSVPrinter(out, format)) { for (Object element : elements) { printer.print(element); } printer.flush(); } catch (IOException e) { throw new IllegalStateException(e); } return out.toString(); }
@Override public void write(Appendable out, List<Table> tables) throws IOException { try (CSVPrinter printer = new CSVPrinter(out, format)) { for (Table table : tables) { for (List<RectangularTextContainer> row : table.getRows()) { List<String> cells = new ArrayList<>(row.size()); for (RectangularTextContainer<?> tc : row) cells.add(tc.getText()); printer.printRecord(cells); } } printer.flush(); } }
public static byte[] exportAsCSV(QueryResult result) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final CSVPrinter csvPrinter; try { final CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC); csvPrinter = new CSVPrinter(new PrintWriter(out), format); csvPrinter.printRecord(result.getMetadata().stream().map(SchemaField::getName) .collect(Collectors.toList())); csvPrinter.printRecords(Iterables.transform(result.getResult(), input -> Iterables.transform(input, input1 -> { if (input1 instanceof List || input1 instanceof Map) { return JsonHelper.encode(input1); } if (input1 instanceof byte[]) { return DatatypeConverter.printBase64Binary((byte[]) input1); } return input1; }))); csvPrinter.flush(); } catch (IOException e) { throw Throwables.propagate(e); } return out.toByteArray(); }
final FileWriter sw = new FileWriter("myfile.csv"); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { printer.printRecord(lines[i]); } printer.flush(); printer.close();
/** * Prints the given values a single record of delimiter separated values followed by the record separator. * * <p> * The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record * separator to the output after printing the record, so there is no need to call {@link #println()}. * </p> * * @param values * values to output. * @throws IOException * If an I/O error occurs */ public void printRecord(final Iterable<?> values) throws IOException { for (final Object value : values) { print(value); } println(); }
private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) throws IOException { CSVFormat format = baseFormat; // Use withHeaderComments first to test CSV-145 format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); format = format.withCommentMarker('#'); format = format.withHeader("Col1", "Col2"); final CSVPrinter csvPrinter = format.print(sw); csvPrinter.printRecord("A", "B"); csvPrinter.printRecord("C", "D"); csvPrinter.close(); return csvPrinter; }
private void includeHeaderIfNecessary(final Record record, final boolean includeOnlySchemaFields) throws IOException { if (headerWritten || !includeHeaderLine) { return; } final Object[] fieldNames; if (includeOnlySchemaFields) { fieldNames = recordSchema.getFieldNames().toArray(new Object[0]); } else { fieldNames = getFieldNames(record); } printer.printRecord(fieldNames); headerWritten = true; }
public static void initializeDataDirectory(String rootDir) throws Exception { loadEntityData(rootDir); // Create app flow mapping file. CSVFormat format = CSVFormat.DEFAULT.withHeader("APP", "USER", "FLOW", "FLOWRUN"); String appFlowMappingFile = rootDir + File.separator + "entities" + File.separator + "cluster1" + File.separator + FileSystemTimelineReaderImpl.APP_FLOW_MAPPING_FILE; try (PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(appFlowMappingFile, true))); CSVPrinter printer = new CSVPrinter(out, format)){ printer.printRecord("app1", "user1", "flow1", 1); printer.printRecord("app2", "user1", "flow1,flow", 1); printer.close(); } (new File(rootDir)).deleteOnExit(); }
@Test public void testCloseWithFlushOn() throws IOException { final Writer writer = mock(Writer.class); final CSVFormat csvFormat = CSVFormat.DEFAULT; final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); csvPrinter.close(true); verify(writer, times(1)).flush(); }
@Override @SuppressFBWarnings("DM_DEFAULT_ENCODING") public void write(ContainerTranslationStatistics statistics) { try { OutputStreamWriter streamWriter = new OutputStreamWriter(System.out); try { CSVPrinter csvPrinter = new CSVPrinter(streamWriter, CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR)); try { writeToCsv(statistics, csvPrinter); csvPrinter.flush(); } finally { csvPrinter.close(); } } finally { streamWriter.close(); } } catch (IOException e) { throw new RuntimeException(e); } }
@Override public void writeItems(final List<Object> list) throws Exception { for (final Object o : list) { if (CSVRecord.class.isInstance(o)) { writer.printRecord(CSVRecord.class.cast(o)); } else if (Iterable.class.isInstance(o)) { writer.printRecord(Iterable.class.cast(o)); } else if (mapperInstance != null) { writer.printRecord(mapperInstance.getValue().toRecord(o)); } else { throw new IllegalStateException("No way to write " + o + ". Does it implement Iterable<String> or did you set up a mapper?"); } } writer.flush(); }
private String toListText(List<String> values) { StringWriter writer = new StringWriter(); CSVPrinter csvWriter = new CSVPrinter(writer); csvWriter.println(values.toArray(new String[]{})); return writer.getBuffer().toString().trim(); }
@Override public void process(JCas jcas) throws AnalysisEngineProcessException { DocumentMetaData dmd = DocumentMetaData.get(jcas); try { OutputStreamWriter os = new OutputStreamWriter( getOutputStream(dmd.getDocumentId(), "." + csvVariantName + ".csv")); CSVPrinter p = new CSVPrinter(os, csvFormat); csvVariant.header(p); csvVariant.convert(jcas, p); p.flush(); os.flush(); IOUtils.closeQuietly(os); } catch (IOException e) { throw new AnalysisEngineProcessException(e); } }
public void setOutput(PrintStream output){ final OutputStreamWriter streamWriter = new OutputStreamWriter(output); try { printer = new CSVPrinter(streamWriter, csvFormat); } catch (IOException e) { throw new ProcessException("Failed to create CSV Printer.", e); } }
@Override public void close() throws IOException { printer.close(); }
@Override public void flush() throws IOException { printer.flush(); }
String outputFile = savePath+".csv"; CSVPrinter csvFilePrinter = null; CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader(); FileWriter fileWriter = new FileWriter(outputFile); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecords(excelParser.getRecords()); fileWriter.flush(); fileWriter.close(); csvFilePrinter.close();