CSVFormat (Apache Commons CSV 1.0 API)

org.apache.commons.csv

## Class CSVFormat

- java.lang.Object
- - org.apache.commons.csv.CSVFormat

- All Implemented Interfaces:
    Serializable

      public final class CSVFormat
      extends Object
      implements Serializable

  Specifies the format of a CSV file and parses input.

  ## Using predefined formats

  You can use one of the predefined formats:

  - `DEFAULT`
  - `EXCEL`
  - `MYSQL`
  - `RFC4180`
  - `TDF`

  For example:

       CSVParser parser = CSVFormat.EXCEL.parse(reader);

  The `CSVParser` provides static methods to parse other input types, for example:

      CSVParser parser = CSVParser.parse(file, StandardCharsets.US_ASCII, CSVFormat.EXCEL);

  ## Defining formats

  You can extend a format by calling the `with` methods. For example:

       CSVFormat.EXCEL
         .withNullString("N/A")
         .withIgnoreSurroundingSpaces(true);

  ## Defining column names

  To define the column names you want to use to access records, write:

       CSVFormat.EXCEL.withHeader("Col1", "Col2", "Col3");

  Calling `withHeader(String...)` let's you use the given names to address values in a `CSVRecord`, and assumes that your CSV source does not contain a first record that also defines column names. If it does, then you are overriding this metadata with your names and you should skip the first record by calling `withSkipHeaderRecord(boolean)` with `true`.

  ## Parsing

  You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write:

       Reader in = ...;
       CSVFormat.EXCEL.withHeader("Col1", "Col2", "Col3").parse(in);

  For other input types, like resources, files, and URLs, use the static methods on `CSVParser`.

  ## Referencing columns safely

  If your source contains a header record, you can simplify your code and safely reference columns, by using `withHeader(String...)` with no arguments:

       CSVFormat.EXCEL.withHeader();

  This causes the parser to read the first record and use its values as column names. Then, call one of the `CSVRecord` get method that takes a String column name argument:

       String value = record.get("Col1");

  This makes your code impervious to changes in column order in the CSV file.

  ## Notes

  This class is immutable.

  Version:
    $Id: CSVFormat.java 1617076 2014-08-10 09:23:01Z britter $
  See Also:
    Serialized Form

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `static CSVFormat` | `DEFAULT` Standard comma separated format, as for `RFC4180` but allowing empty lines.
    `static CSVFormat` | `EXCEL` Excel file format (using a comma as the value delimiter).
    `static CSVFormat` | `MYSQL` Default MySQL format used by the `SELECT INTO OUTFILE` and `LOAD DATA INFILE` operations.
    `static CSVFormat` | `RFC4180` Comma separated format as defined by RFC 4180.
    `static CSVFormat` | `TDF` Tab-delimited format.

  - ### Method Summary

    All Methods Static Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `boolean` | `equals(Object obj)`
    `String` | `format(Object... values)` Formats the specified values.
    `boolean` | `getAllowMissingColumnNames()` Specifies whether missing column names are allowed when parsing the header line.
    `Character` | `getCommentMarker()` Returns the character marking the start of a line comment.
    `char` | `getDelimiter()` Returns the character delimiting the values (typically ';', ',' or '\t').
    `Character` | `getEscapeCharacter()` Returns the escape character.
    `String[]` | `getHeader()` Returns a copy of the header array.
    `boolean` | `getIgnoreEmptyLines()` Specifies whether empty lines between records are ignored when parsing input.
    `boolean` | `getIgnoreSurroundingSpaces()` Specifies whether spaces around values are ignored when parsing input.
    `String` | `getNullString()` Gets the String to convert to and from `null`.
    `Character` | `getQuoteCharacter()` Returns the character used to encapsulate values containing special characters.
    `QuoteMode` | `getQuoteMode()` Returns the quote policy output fields.
    `String` | `getRecordSeparator()` Returns the record separator delimiting output records.
    `boolean` | `getSkipHeaderRecord()` Returns whether to skip the header record.
    `int` | `hashCode()`
    `boolean` | `isCommentMarkerSet()` Specifies whether comments are supported by this format.
    `boolean` | `isEscapeCharacterSet()` Returns whether escape are being processed.
    `boolean` | `isNullStringSet()` Returns whether a nullString has been defined.
    `boolean` | `isQuoteCharacterSet()` Returns whether a quoteChar has been defined.
    `static CSVFormat` | `newFormat(char delimiter)` Creates a new CSV format with the specified delimiter.
    `CSVParser` | `parse(Reader in)` Parses the specified content.
    `CSVPrinter` | `print(Appendable out)` Prints to the specified output.
    `String` | `toString()`
    `CSVFormat` | `withAllowMissingColumnNames(boolean allowMissingColumnNames)` Sets the missing column names behavior of the format.
    `CSVFormat` | `withCommentMarker(char commentMarker)` Sets the comment start marker of the format to the specified character.
    `CSVFormat` | `withCommentMarker(Character commentMarker)` Sets the comment start marker of the format to the specified character.
    `CSVFormat` | `withDelimiter(char delimiter)` Sets the delimiter of the format to the specified character.
    `CSVFormat` | `withEscape(char escape)` Sets the escape character of the format to the specified character.
    `CSVFormat` | `withEscape(Character escape)` Sets the escape character of the format to the specified character.
    `CSVFormat` | `withHeader(String... header)` Sets the header of the format.
    `CSVFormat` | `withIgnoreEmptyLines(boolean ignoreEmptyLines)` Sets the empty line skipping behavior of the format.
    `CSVFormat` | `withIgnoreSurroundingSpaces(boolean ignoreSurroundingSpaces)` Sets the trimming behavior of the format.
    `CSVFormat` | `withNullString(String nullString)` Performs conversions to and from null for strings on input and output.
    `CSVFormat` | `withQuote(char quoteChar)` Sets the quoteChar of the format to the specified character.
    `CSVFormat` | `withQuote(Character quoteChar)` Sets the quoteChar of the format to the specified character.
    `CSVFormat` | `withQuoteMode(QuoteMode quoteModePolicy)` Sets the output quote policy of the format to the specified value.
    `CSVFormat` | `withRecordSeparator(char recordSeparator)` Sets the record separator of the format to the specified character.
    `CSVFormat` | `withRecordSeparator(String recordSeparator)` Sets the record separator of the format to the specified String.
    `CSVFormat` | `withSkipHeaderRecord(boolean skipHeaderRecord)` Sets whether to skip the header record.

    - ### Methods inherited from class java.lang.Object

      `clone, finalize, getClass, notify, notifyAll, wait, wait, wait`

- - ### Field Detail

    - #### DEFAULT

          public static final CSVFormat DEFAULT

      Standard comma separated format, as for `RFC4180` but allowing empty lines.

      Settings are:

      - withDelimiter(',')
      - withQuoteChar('"')
      - withRecordSeparator("\r\n")
      - withIgnoreEmptyLines(true)

    - #### RFC4180

          public static final CSVFormat RFC4180

      Comma separated format as defined by RFC 4180.

      Settings are:

      - withDelimiter(',')
      - withQuoteChar('"')
      - withRecordSeparator("\r\n")
      - withIgnoreEmptyLines(false)

    - #### EXCEL

          public static final CSVFormat EXCEL

      Excel file format (using a comma as the value delimiter). Note that the actual value delimiter used by Excel is locale dependent, it might be necessary to customize this format to accommodate to your regional settings.

      For example for parsing or generating a CSV file on a French system the following format will be used:

           CSVFormat fmt = CSVFormat.EXCEL.withDelimiter(';');

      Settings are:

      - withDelimiter(',')
      - withQuoteChar('"')
      - withRecordSeparator("\r\n")
      - withIgnoreEmptyLines(false)

      Note: this is currently the same as `RFC4180`.

    - #### TDF

          public static final CSVFormat TDF

      Tab-delimited format.

      Settings are:

      - withDelimiter('\t')
      - withQuoteChar('"')
      - withRecordSeparator("\r\n")
      - withIgnoreSurroundingSpaces(true)

    - #### MYSQL

          public static final CSVFormat MYSQL

      Default MySQL format used by the `SELECT INTO OUTFILE` and `LOAD DATA INFILE` operations.

      This is a tab-delimited format with a LF character as the line separator. Values are not quoted and special characters are escaped with '\'.

      Settings are:

      - withDelimiter('\t')
      - withQuoteChar(null)
      - withRecordSeparator('\n')
      - withIgnoreEmptyLines(false)
      - withEscape('\\')
      See Also:
        http://dev.mysql.com/doc/refman/5.1/en/load-data.html

  - ### Method Detail

    - #### newFormat

          public static CSVFormat newFormat(char delimiter)

      Creates a new CSV format with the specified delimiter.

      Use this method if you want to create a CSVFormat from scratch. All fields but the delimiter will be initialized with null/false.

      Parameters:
        `delimiter` - the char used for value separation, must not be a line break character
      Returns:
        a new CSV format.
      Throws:
        `IllegalArgumentException` - if the delimiter is a line break character
      See Also:
        `DEFAULT`, `RFC4180`, `MYSQL`, `EXCEL`, `TDF`

    - #### equals

          public boolean equals(Object obj)

      Overrides:
        `equals` in class `Object`

    - #### format

          public String format(Object... values)

      Formats the specified values.
      Parameters:
        `values` - the values to format
      Returns:
        the formatted values

    - #### getCommentMarker

          public Character getCommentMarker()

      Returns the character marking the start of a line comment.
      Returns:
        the comment start marker, may be `null`

    - #### getDelimiter

          public char getDelimiter()

      Returns the character delimiting the values (typically ';', ',' or '\t').
      Returns:
        the delimiter character

    - #### getEscapeCharacter

          public Character getEscapeCharacter()

      Returns the escape character.
      Returns:
        the escape character, may be `null`

    - #### getHeader

          public String[] getHeader()

      Returns a copy of the header array.
      Returns:
        a copy of the header array; `null` if disabled, the empty array if to be read from the file

    - #### getAllowMissingColumnNames

          public boolean getAllowMissingColumnNames()

      Specifies whether missing column names are allowed when parsing the header line.
      Returns:
        `true` if missing column names are allowed when parsing the header line, `false` to throw an `IllegalArgumentException`.

    - #### getIgnoreEmptyLines

          public boolean getIgnoreEmptyLines()

      Specifies whether empty lines between records are ignored when parsing input.
      Returns:
        `true` if empty lines between records are ignored, `false` if they are turned into empty records.

    - #### getIgnoreSurroundingSpaces

          public boolean getIgnoreSurroundingSpaces()

      Specifies whether spaces around values are ignored when parsing input.
      Returns:
        `true` if spaces around values are ignored, `false` if they are treated as part of the value.

    - #### getNullString

          public String getNullString()

      Gets the String to convert to and from `null`.
      - Reading: Converts strings equal to the given `nullString` to `null` when reading records.
      - Writing: Writes `null` as the given `nullString` when writing records.
      Returns:
        the String to convert to and from `null`. No substitution occurs if `null`

    - #### getQuoteCharacter

          public Character getQuoteCharacter()

      Returns the character used to encapsulate values containing special characters.
      Returns:
        the quoteChar character, may be `null`

    - #### getQuoteMode

          public QuoteMode getQuoteMode()

      Returns the quote policy output fields.
      Returns:
        the quote policy

    - #### getRecordSeparator

          public String getRecordSeparator()

      Returns the record separator delimiting output records.
      Returns:
        the record separator

    - #### getSkipHeaderRecord

          public boolean getSkipHeaderRecord()

      Returns whether to skip the header record.
      Returns:
        whether to skip the header record.

    - #### hashCode

          public int hashCode()

      Overrides:
        `hashCode` in class `Object`

    - #### isCommentMarkerSet

          public boolean isCommentMarkerSet()

      Specifies whether comments are supported by this format. Note that the comment introducer character is only recognized at the start of a line.
      Returns:
        `true` is comments are supported, `false` otherwise

    - #### isEscapeCharacterSet

          public boolean isEscapeCharacterSet()

      Returns whether escape are being processed.
      Returns:
        `true` if escapes are processed

    - #### isNullStringSet

          public boolean isNullStringSet()

      Returns whether a nullString has been defined.
      Returns:
        `true` if a nullString is defined

    - #### isQuoteCharacterSet

          public boolean isQuoteCharacterSet()

      Returns whether a quoteChar has been defined.
      Returns:
        `true` if a quoteChar is defined

    - #### parse

          public CSVParser parse(Reader in)
                          throws IOException

      Parses the specified content.

      See also the various static parse methods on `CSVParser`.

      Parameters:
        `in` - the input stream
      Returns:
        a parser over a stream of `CSVRecord`s.
      Throws:
        `IOException` - If an I/O error occurs

    - #### print

          public CSVPrinter print(Appendable out)
                           throws IOException

      Prints to the specified output.

      See also `CSVPrinter`.

      Parameters:
        `out` - the output
      Returns:
        a printer to an output
      Throws:
        `IOException` - thrown if the optional header cannot be printed.

    - #### toString

          public String toString()

      Overrides:
        `toString` in class `Object`

    - #### withCommentMarker

          public CSVFormat withCommentMarker(char commentMarker)

      Sets the comment start marker of the format to the specified character. Note that the comment start character is only recognized at the start of a line.
      Parameters:
        `commentMarker` - the comment start marker
      Returns:
        A new CSVFormat that is equal to this one but with the specified character as the comment start marker
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withCommentMarker

          public CSVFormat withCommentMarker(Character commentMarker)

      Sets the comment start marker of the format to the specified character. Note that the comment start character is only recognized at the start of a line.
      Parameters:
        `commentMarker` - the comment start marker, use `null` to disable
      Returns:
        A new CSVFormat that is equal to this one but with the specified character as the comment start marker
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withDelimiter

          public CSVFormat withDelimiter(char delimiter)

      Sets the delimiter of the format to the specified character.
      Parameters:
        `delimiter` - the delimiter character
      Returns:
        A new CSVFormat that is equal to this with the specified character as delimiter
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withEscape

          public CSVFormat withEscape(char escape)

      Sets the escape character of the format to the specified character.
      Parameters:
        `escape` - the escape character
      Returns:
        A new CSVFormat that is equal to his but with the specified character as the escape character
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withEscape

          public CSVFormat withEscape(Character escape)

      Sets the escape character of the format to the specified character.
      Parameters:
        `escape` - the escape character, use `null` to disable
      Returns:
        A new CSVFormat that is equal to this but with the specified character as the escape character
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withHeader

          public CSVFormat withHeader(String... header)

      Sets the header of the format. The header can either be parsed automatically from the input file with:

           CSVFormat format = aformat.withHeader();

      or specified manually with:

           CSVFormat format = aformat.withHeader("name", "email", "phone");

      Parameters:
        `header` - the header, `null` if disabled, empty if parsed automatically, user specified otherwise.
      Returns:
        A new CSVFormat that is equal to this but with the specified header
      See Also:
        `withSkipHeaderRecord(boolean)`

    - #### withAllowMissingColumnNames

          public CSVFormat withAllowMissingColumnNames(boolean allowMissingColumnNames)

      Sets the missing column names behavior of the format.
      Parameters:
        `allowMissingColumnNames` - the missing column names behavior, `true` to allow missing column names in the header line, `false` to cause an `IllegalArgumentException` to be thrown.
      Returns:
        A new CSVFormat that is equal to this but with the specified missing column names behavior.

    - #### withIgnoreEmptyLines

          public CSVFormat withIgnoreEmptyLines(boolean ignoreEmptyLines)

      Sets the empty line skipping behavior of the format.
      Parameters:
        `ignoreEmptyLines` - the empty line skipping behavior, `true` to ignore the empty lines between the records, `false` to translate empty lines to empty records.
      Returns:
        A new CSVFormat that is equal to this but with the specified empty line skipping behavior.

    - #### withIgnoreSurroundingSpaces

          public CSVFormat withIgnoreSurroundingSpaces(boolean ignoreSurroundingSpaces)

      Sets the trimming behavior of the format.
      Parameters:
        `ignoreSurroundingSpaces` - the trimming behavior, `true` to remove the surrounding spaces, `false` to leave the spaces as is.
      Returns:
        A new CSVFormat that is equal to this but with the specified trimming behavior.

    - #### withNullString

          public CSVFormat withNullString(String nullString)

      Performs conversions to and from null for strings on input and output.
      - Reading: Converts strings equal to the given `nullString` to `null` when reading records.
      - Writing: Writes `null` as the given `nullString` when writing records.
      Parameters:
        `nullString` - the String to convert to and from `null`. No substitution occurs if `null`
      Returns:
        A new CSVFormat that is equal to this but with the specified null conversion string.

    - #### withQuote

          public CSVFormat withQuote(char quoteChar)

      Sets the quoteChar of the format to the specified character.
      Parameters:
        `quoteChar` - the quoteChar character
      Returns:
        A new CSVFormat that is equal to this but with the specified character as quoteChar
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withQuote

          public CSVFormat withQuote(Character quoteChar)

      Sets the quoteChar of the format to the specified character.
      Parameters:
        `quoteChar` - the quoteChar character, use `null` to disable
      Returns:
        A new CSVFormat that is equal to this but with the specified character as quoteChar
      Throws:
        `IllegalArgumentException` - thrown if the specified character is a line break

    - #### withQuoteMode

          public CSVFormat withQuoteMode(QuoteMode quoteModePolicy)

      Sets the output quote policy of the format to the specified value.
      Parameters:
        `quoteModePolicy` - the quote policy to use for output.
      Returns:
        A new CSVFormat that is equal to this but with the specified quote policy

    - #### withRecordSeparator

          public CSVFormat withRecordSeparator(char recordSeparator)

      Sets the record separator of the format to the specified character.

      Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and "\r\n"

      Parameters:
        `recordSeparator` - the record separator to use for output.
      Returns:
        A new CSVFormat that is equal to this but with the the specified output record separator

    - #### withRecordSeparator

          public CSVFormat withRecordSeparator(String recordSeparator)

      Sets the record separator of the format to the specified String.

      Note: This setting is only used during printing and does not affect parsing. Parsing currently only works for inputs with '\n', '\r' and "\r\n"

      Parameters:
        `recordSeparator` - the record separator to use for output.
      Returns:
        A new CSVFormat that is equal to this but with the the specified output record separator
      Throws:
        `IllegalArgumentException` - if recordSeparator is none of CR, LF or CRLF

    - #### withSkipHeaderRecord

          public CSVFormat withSkipHeaderRecord(boolean skipHeaderRecord)

      Sets whether to skip the header record.
      Parameters:
        `skipHeaderRecord` - whether to skip the header record.
      Returns:
        A new CSVFormat that is equal to this but with the the specified skipHeaderRecord setting.
      See Also:
        `withHeader(String...)`

Copyright © 2014 The Apache Software Foundation. All rights reserved.