public static String[] parseAsCsv(String key, String value, Function<String, String> valueProcessor) { String cleanValue = MultivalueProperty.trimFieldsAndRemoveEmptyFields(value); List<String> result = new ArrayList<>(); try (CSVParser csvParser = CSVFormat.RFC4180 .withHeader((String) null) .withIgnoreEmptyLines() .withIgnoreSurroundingSpaces() .parse(new StringReader(cleanValue))) { List<CSVRecord> records = csvParser.getRecords(); if (records.isEmpty()) { return ArrayUtils.EMPTY_STRING_ARRAY; } processRecords(result, records, valueProcessor); return result.toArray(new String[result.size()]); } catch (IOException e) { throw new IllegalStateException("Property: '" + key + "' doesn't contain a valid CSV value: '" + value + "'", e); } }
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; }
public CSVRecordReader(final InputStream in, final ComponentLog logger, final RecordSchema schema, final CSVFormat csvFormat, final boolean hasHeader, final boolean ignoreHeader, final String dateFormat, final String timeFormat, final String timestampFormat, final String encoding) throws IOException { super(logger, schema, hasHeader, ignoreHeader, dateFormat, timeFormat, timestampFormat); final Reader reader = new InputStreamReader(new BOMInputStream(in), encoding); CSVFormat withHeader; if (hasHeader) { withHeader = csvFormat.withSkipHeaderRecord(); if (ignoreHeader) { withHeader = withHeader.withHeader(schema.getFieldNames().toArray(new String[0])); } else { withHeader = withHeader.withFirstRecordAsHeader(); } } else { withHeader = csvFormat.withHeader(schema.getFieldNames().toArray(new String[0])); } csvParser = new CSVParser(reader, withHeader); }
@BeforeClass public void setUp() throws Exception { FileUtils.forceMkdir(TEMP_DIR); try (FileWriter fileWriter = new FileWriter(DATA_FILE); CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader(COLUMNS))) { for (Object[] record : RECORDS) { csvPrinter.printRecord(record[0], StringUtils.join((int[]) record[1], CSVRecordReaderConfig.DEFAULT_MULTI_VALUE_DELIMITER)); } } }
_format = CSVFormat.DEFAULT.withDelimiter(CSVRecordReaderConfig.DEFAULT_DELIMITER).withHeader(); _multiValueDelimiter = CSVRecordReaderConfig.DEFAULT_MULTI_VALUE_DELIMITER; } else { String csvHeader = config.getHeader(); if (csvHeader == null) { format = format.withHeader(); } else { format = format.withHeader(StringUtils.split(csvHeader, delimiter));
.withHeader() .withDelimiter(delimiter) .withQuote(quote)
/** * Returns a new {@code CSVFormat} with the header of the format set from the result set metadata. The header can * either be parsed automatically from the input file with: * * <pre> * CSVFormat format = aformat.withHeader(); * </pre> * * or specified manually with: * * <pre> * CSVFormat format = aformat.withHeader(resultSet); * </pre> * <p> * The header is also used by the {@link CSVPrinter}. * </p> * * @param resultSet * the resultSet for the header, {@code null} if disabled, empty if parsed automatically, user specified * otherwise. * * @return A new CSVFormat that is equal to this but with the specified header * @throws SQLException * SQLException if a database access error occurs or this method is called on a closed result set. * @since 1.1 */ public CSVFormat withHeader(final ResultSet resultSet) throws SQLException { return withHeader(resultSet != null ? resultSet.getMetaData() : null); }
return withHeader(labels);
return withHeader(header);
/** * Returns a new {@code CSVFormat} using the first record as header. * * <p> * Calling this method is equivalent to calling: * </p> * * <pre> * CSVFormat format = aFormat.withHeader().withSkipHeaderRecord(); * </pre> * * @return A new CSVFormat that is equal to this but using the first record as header. * @see #withSkipHeaderRecord(boolean) * @see #withHeader(String...) * @since 1.3 */ public CSVFormat withFirstRecordAsHeader() { return withHeader().withSkipHeaderRecord(); }
try (CSVParser parser = new CSVParser(new StringReader(content), getCSVFormat().withHeader())) { Set<String> columns = parser.getHeaderMap().keySet(); Map<String, Field> fieldMap = getFieldMap(objectType);
.DEFAULT .withRecordSeparator("\n") .withHeader(Header.class) .withQuoteMode(QuoteMode.ALL)); ) {
case IN_LINE: format = format.withHeader(new String[0]); break; case SUPPLIED_BY_USER: format = format.withHeader(columns.toArray(new String[columns.size()])); break; default:
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; }
final CSVParser parser = new CSVParser(in, CSVFormat.DEFAULT.withHeader());
@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 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()); } } }
@Test public void testHeader() throws IOException { final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } }
@Test public void testSkipHeaderRecordFalse() throws IOException { // functionally identical to testHeader, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); } }
@Test public void testSkipHeaderRecordTrue() throws IOException { // functionally identical to testHeaderNotSet, used to test CSV-153 final StringWriter sw = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { printer.printRecord("a", "b", "c"); printer.printRecord("x", "y", "z"); assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); } }