From b6f0655a7107b9c817f10a215cea4da90b27281f Mon Sep 17 00:00:00 2001 From: Benedikt Ritter Date: Tue, 3 May 2016 18:43:33 +0000 Subject: [PATCH] CSV-179: Add shortcut method for using first record as header to CSVFormat git-svn-id: https://svn.apache.org/repos/asf/commons/proper/csv/trunk@1742175 13f79535-47bb-0310-9956-ffa450edef68 --- src/changes/changes.xml | 1 + .../org/apache/commons/csv/CSVFormat.java | 19 +++++++++++++++++++ .../org/apache/commons/csv/CSVFormatTest.java | 7 +++++++ 3 files changed, 27 insertions(+) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index dbde654b..722ed206 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -39,6 +39,7 @@ + Add shortcut method for using first record as header to CSVFormat Add withHeader(Class<? extends Enum>) to CSVFormat Comment line hides next record; update Javadoc to make behaviour clear CSVPrinter doesn't skip creation of header record if skipHeaderRecord is set to true diff --git a/src/main/java/org/apache/commons/csv/CSVFormat.java b/src/main/java/org/apache/commons/csv/CSVFormat.java index a1756bc0..27508b97 100644 --- a/src/main/java/org/apache/commons/csv/CSVFormat.java +++ b/src/main/java/org/apache/commons/csv/CSVFormat.java @@ -1074,6 +1074,25 @@ public final class CSVFormat implements Serializable { allowMissingColumnNames, ignoreHeaderCase, trim, trailingDelimiter); } + /** + * Returns a new {@code CSVFormat} using the first record as header. + * + *

+ * Calling this method is equivalent to calling: + *

+ *
+     * CSVFormat format = aFormat.withHeader().withSkipHeaderRecord();
+     * 
+ * + * @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(); + } + /** * 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: diff --git a/src/test/java/org/apache/commons/csv/CSVFormatTest.java b/src/test/java/org/apache/commons/csv/CSVFormatTest.java index 0196c436..ac4abf0b 100644 --- a/src/test/java/org/apache/commons/csv/CSVFormatTest.java +++ b/src/test/java/org/apache/commons/csv/CSVFormatTest.java @@ -436,6 +436,13 @@ public class CSVFormatTest { assertEquals(CRLF, formatWithRecordSeparator.getRecordSeparator()); } + @Test + public void testWithFirstRecordAsHeader() throws Exception { + final CSVFormat formatWithFirstRecordAsHeader = CSVFormat.DEFAULT.withFirstRecordAsHeader(); + assertTrue(formatWithFirstRecordAsHeader.getSkipHeaderRecord()); + assertTrue(formatWithFirstRecordAsHeader.getHeader().length == 0); + } + public enum Header { Name, Email, Phone }