/** * Prints the string as the next value on the line. The value will be escaped or encapsulated as needed. * * @param value * value to be output. * @throws IOException * If an I/O error occurs */ public void print(final Object value) throws IOException { format.print(value, out, newRecord); newRecord = false; }
/** * Prints the given {@code values} to {@code out} as a single record of delimiter separated values followed by the * record separator. * * <p> * The values will be quoted if needed. Quotes and new-line 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(Appendable)}. * </p> * * @param out * where to write. * @param values * values to output. * @throws IOException * If an I/O error occurs. * @since 1.4 */ public void printRecord(final Appendable out, final Object... values) throws IOException { for (int i = 0; i < values.length; i++) { print(values[i], out, i == 0); } println(out); }
/** * Prints to the specified output. * * <p> * See also {@link CSVPrinter}. * </p> * * @param out * the output. * @param charset * A charset. * @return a printer to an output. * @throws IOException * thrown if the optional header cannot be printed. * @since 1.5 */ public CSVPrinter print(final Path out, final Charset charset) throws IOException { return print(Files.newBufferedWriter(out, charset)); }
this.print(value, charSequence, 0, charSequence.length(), out, newRecord);
@Test public void testPrintToPathWithDefaultCharset() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); }
@Test public void testPrintToFileWithDefaultCharset() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); }
public String toCsv(Csv... records) { if (records != null && records.length > 0) { String[] header = records[0].getCsvHeader(); StringWriter writer = new StringWriter(); try (CSVPrinter printer = getCSVFormat().withHeader(header).print(writer)) { for (Csv record : records) { Object [] data = record.getCsvData(); if (data == null || data.length == 0) { log.debug("Skipping null or empty record"); continue; } for (Object column : data) { printer.print(objectToString(column)); } printer.println(); } } catch (IOException e) { log.error("Failed to generate CSV", e); } return writer.toString(); } return null; }
@Test public void testPrintToFileWithCharsetUtf16Be() throws IOException { final File file = File.createTempFile(getClass().getName(), ".csv"); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { printer.printRecord("a", "b\\c"); } assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); }
@Test public void testPrint() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { printer.printRecord("a", "b\\c"); assertEquals("a,b\\c" + recordSeparator, sw.toString()); } }
@Test public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection();) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { printer.printRecords(resultSet); } } assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); }
@Test public void testPrintRecordsWithObjectArray() throws IOException { final CharArrayWriter charArrayWriter = new CharArrayWriter(0); try (CSVPrinter csvPrinter = CSVFormat.INFORMIX_UNLOAD.print(charArrayWriter)) { final HashSet<BatchUpdateException> hashSet = new HashSet<>(); final Object[] objectArray = new Object[6]; objectArray[3] = hashSet; csvPrinter.printRecords(objectArray); } assertEquals(6, charArrayWriter.size()); assertEquals("\n\n\n\n\n\n", charArrayWriter.toString()); }
@Test public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { final StringWriter sw = new StringWriter(); Class.forName("org.h2.Driver"); try (final Connection connection = geH2Connection()) { setUpTable(connection); try (final Statement stmt = connection.createStatement(); final ResultSet resultSet = stmt.executeQuery("select ID, NAME from TEST"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { printer.printRecords(resultSet); assertEquals("ID,NAME" + recordSeparator + "1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); } } }
/** * Prints the string as the next value on the line. The value will be escaped or encapsulated as needed. * * @param value * value to be output. * @throws IOException * If an I/O error occurs */ public void print(final Object value) throws IOException { format.print(value, out, newRecord); newRecord = false; }
/** * Prints the string as the next value on the line. The value will be escaped or encapsulated as needed. * * @param value * value to be output. * @throws IOException * If an I/O error occurs */ public void print(final Object value) throws IOException { format.print(value, out, newRecord); newRecord = false; }
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; }
@Override public void write(Map<String, String> line) throws IOException { if (csvPrinter == null) { headers = line.keySet().toArray(new String[line.size()]); csvPrinter = CSVFormat.DEFAULT.withDelimiter(delimiter).withHeader(headers).print(writer); } String[] values = new String[headers.length]; for (int i = 0; i < headers.length; i++) { values[i] = line.get(headers[i]); } csvPrinter.printRecord(values); }
@Override public void write(Map<String, Object> line) throws IOException { if (csvPrinter == null) { headers = line.keySet().toArray(new String[line.size()]); csvPrinter = CSVFormat.DEFAULT.withDelimiter(delimiter).withHeader(headers).print(writer); } Object[] values = new Object[headers.length]; for (int i = 0; i < headers.length; i++) { values[i] = line.get(headers[i]); } csvPrinter.printRecord(values); }
@Override public void initialize(Arguments args) throws DirectiveParseException { this.column = ((ColumnName) args.value("column")).value(); try { this.writer = CSVFormat.DEFAULT.print(new StringWriter()); } catch (IOException e) { throw new DirectiveParseException(toString() + " : " + "Unable to create CSV writer. " + e.getMessage()); } }
@ProcessElement public void processElement(ProcessContext c) throws IOException { // Join the strings with the delimiter. IndexedRecord in = c.element(); int size = in.getSchema().getFields().size(); for (int i = 0; i < size; i++) { Object valueToWrite = in.get(i); if (valueToWrite instanceof ByteBuffer) valueToWrite = new String(((ByteBuffer) valueToWrite).array()); format.print(valueToWrite, sb, sb.length() == 0); } c.output(KV.of(NullWritable.get(), new Text(sb.toString()))); sb.setLength(0); } }
public static String beamRow2CsvLine(Row row, CSVFormat csvFormat) { StringWriter writer = new StringWriter(); try (CSVPrinter printer = csvFormat.print(writer)) { for (int i = 0; i < row.getFieldCount(); i++) { printer.print(row.getValue(i).toString()); } printer.println(); } catch (IOException e) { throw new IllegalArgumentException("encodeRecord failed!", e); } return writer.toString(); }