Top Description Inners Fields Constructors Methods
org.apache.commons.csv

public final Class CSVFormat

extends Object
implements Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable
Static Imports
org.apache.commons.io.IOUtils.EOF

Specifies the format of a CSV file for parsing and writing.

Using predefined formats

You can use one of the predefined formats:

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 set methods. For example:

CSVFormat.EXCEL.builder().setNullString("N/A").setIgnoreSurroundingSpaces(true).get();

Defining column names

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

CSVFormat.EXCEL.builder().setHeader("Col1", "Col2", "Col3").get();

Calling Builder#setHeader(String...) lets 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 Builder#setSkipHeaderRecord(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.builder().setHeader("Col1", "Col2", "Col3").get().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 Builder#setHeader(String...) with no arguments:

CSVFormat.EXCEL.builder().setHeader().get();

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.

Serialization

This class implements the Serializable interface with the following caveats:

The serialVersionUID values are:

Notes

This class is immutable.

Not all settings are used for both parsing and writing.

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
CSVFormat.Builder

Builds CSVFormat instances.

public static enum
CSVFormat.Predefined

Predefines formats.

Field Summary

Modifier and TypeField and Description
private final boolean
allowMissingColumnNames

Whether missing column names are allowed when parsing the header line.

private final boolean
autoFlush

Whether to flush on close.

private final Character
commentMarker

Set to null if commenting is disabled.

public static final CSVFormat
DEFAULT

Standard Comma Separated Value format, as for RFC4180 but allowing empty lines.

private final String
delimiter

The character delimiting the values (typically ";", "," or "\t").

private final DuplicateHeaderMode
duplicateHeaderMode

How duplicate headers are handled.

private final Character
escapeCharacter

Set to null if escaping is disabled.

public static final CSVFormat
EXCEL

Microsoft Excel file format (using a comma as the value delimiter).

private final String[]
headerComments

Array of header comment lines.

private final String[]
headers

Array of header column names.

private final boolean
ignoreEmptyLines

Whether empty lines between records are ignored when parsing input.

private final boolean
ignoreHeaderCase

Should ignore header names case.

private final boolean
ignoreSurroundingSpaces

Should leading/trailing spaces be ignored around values?.

public static final CSVFormat
INFORMIX_UNLOAD

Default Informix CSV UNLOAD format used by the UNLOAD TO file_name operation.

public static final CSVFormat
INFORMIX_UNLOAD_CSV

Default Informix CSV UNLOAD format used by the UNLOAD TO file_name operation (escaping is disabled.)

This is a comma-delimited format with an LF character as the line separator.

private final boolean
lenientEof

Whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.

private final long
maxRows

The maximum number of rows to process, excluding the header row.

public static final CSVFormat
MONGODB_CSV

Default MongoDB CSV format used by the mongoexport operation.

public static final CSVFormat
MONGODB_TSV

Default MongoDB TSV format used by the mongoexport operation.

public static final CSVFormat
MYSQL

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

private final String
nullString

The string to be used for null values.

public static final CSVFormat
ORACLE

Default Oracle format used by the SQL*Loader utility.

public static final CSVFormat
POSTGRESQL_CSV

Default PostgreSQL CSV format used by the COPY operation.

public static final CSVFormat
POSTGRESQL_TEXT

Default PostgreSQL Text format used by the COPY operation.

private final Character
quoteCharacter

Set to null if quoting is disabled.

private final String
quotedNullString

Set to quoteCharacter + nullString + quoteCharacter

private final QuoteMode
quoteMode

The quote policy output fields.

private final String
recordSeparator

For output.

public static final CSVFormat
RFC4180

Comma separated format as defined by RFC 4180.

private static final long
private final boolean
skipHeaderRecord

Whether to skip the header record.

public static final CSVFormat
TDF

Tab-delimited format (TDF).

private final boolean
trailingData

Whether reading trailing data is allowed in records, helps Excel compatibility.

private final boolean
trailingDelimiter

Whether to add a trailing delimiter.

private final boolean
trim

Whether to trim leading and trailing blanks.

Constructor Summary

AccessConstructor and Description
private
CSVFormat(final CSVFormat.Builder builder)

Method Summary

Modifier and TypeMethod and Description
private void
append(final char c, final Appendable appendable)

private void
append(final CharSequence csq, final Appendable appendable)

public CSVFormat.Builder

Returns:

a new Builder.
builder
()

Creates a new Builder for this instance.

pack-priv static <
The array element type.
T
>
T[]

Returns:

the cloned array.
clone
(final T...
the source array
values
)

Null-safe clone of an array.

private static boolean

Returns:

true if c contains a line break character
contains
(final String
the string to check.
source
,
final char
the character to search.
searchCh
)

Returns true if the given string contains the search char.

private static boolean

Returns:

true if c contains a line break character.
containsLineBreak
(final String
the string to check.
source
)

Returns true if the given string contains a line break character.

pack-priv static CSVFormat

Returns:

a copy of the given instance or null if the input is null.
copy
(final CSVFormat format)

Creates a null-safe copy of the given instance.

pack-priv CSVFormat

Returns:

a copy of this instance.
copy
()

Creates a copy of this instance.

public boolean
equals(final Object
the reference object with which to compare.
obj
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

private void
escape(final char c, final Appendable appendable)

public String

Returns:

the formatted values.
format
(final Object...
the values to format.
values
)

Formats the specified values as a CSV record string.

private String
format_(final Object... values)

public boolean

Returns:

whether duplicate header names are allowed
getAllowDuplicateHeaderNames
()
Deprecated Use getDuplicateHeaderMode().

Gets whether duplicate names are allowed in the headers.

public boolean

Returns:

true if missing column names are allowed when parsing the header line, false to throw an IllegalArgumentException.
getAllowMissingColumnNames
()

Gets whether missing column names are allowed when parsing the header line.

public boolean

Returns:

whether to flush on close.
getAutoFlush
()

Gets whether to flush on close.

public Character

Returns:

the comment start marker, may be null
getCommentMarker
()

Gets the comment marker character, null disables comments.

public char

Returns:

the first delimiter character.
getDelimiter
()
Deprecated Use getDelimiterString().

Gets the first character delimiting the values (typically ';', ',' or '\t').

pack-priv char[]

Returns:

the delimiter.
getDelimiterCharArray
()

Gets the character delimiting the values (typically ";", "," or "\t").

public String

Returns:

the delimiter.
getDelimiterString
()

Gets the character delimiting the values (typically ";", "," or "\t").

public DuplicateHeaderMode

Returns:

if duplicate header values are allowed, allowed conditionally, or disallowed.
getDuplicateHeaderMode
()

Gets how duplicate headers are handled.

pack-priv char

Returns:

the escape character, may be 0
getEscapeChar
()

Gets the escape character.

public Character

Returns:

the escape character, may be null
getEscapeCharacter
()

Gets the escape character.

public String[]

Returns:

a copy of the header array; null if disabled, the empty array if to be read from the file
getHeader
()

Gets a copy of the header array.

public String[]

Returns:

a copy of the header comment array; null if disabled.
getHeaderComments
()

Gets a copy of the header comment array to write before the CSV data.

public boolean

Returns:

true if empty lines between records are ignored, false if they are turned into empty records.
getIgnoreEmptyLines
()

Gets whether empty lines between records are ignored when parsing input.

public boolean

Returns:

true if header names cases are ignored, false if they are case-sensitive.
getIgnoreHeaderCase
()

Gets whether header names will be accessed ignoring case when parsing input.

public boolean

Returns:

true if spaces around values are ignored, false if they are treated as part of the value.
getIgnoreSurroundingSpaces
()

Gets whether spaces around values are ignored when parsing input.

public boolean

Returns:

whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.
getLenientEof
()

Gets whether reading end-of-file is allowed even when input is malformed, helps Excel compatibility.

public long

Returns:

The maximum number of rows to process, excluding the header row.
getMaxRows
()

Gets the maximum number of rows to process, excluding the header row.

public String

Returns:

the String to convert to and from null. No substitution occurs if null
getNullString
()

Gets the String to convert to and from null.

public Character

Returns:

the quoteChar character, may be null
getQuoteCharacter
()

Gets the character used to encapsulate values containing special characters.

public QuoteMode

Returns:

the quote policy
getQuoteMode
()

Gets the quote policy output fields.

public String

Returns:

the record separator
getRecordSeparator
()

Gets the record separator delimiting output records.

public boolean

Returns:

whether to skip the header record.
getSkipHeaderRecord
()

Gets whether to skip the header record.

public boolean

Returns:

whether reading trailing data is allowed in records, helps Excel compatibility.
getTrailingData
()

Gets whether reading trailing data is allowed in records, helps Excel compatibility.

public boolean

Returns:

whether to add a trailing delimiter.
getTrailingDelimiter
()

Gets whether to add a trailing delimiter.

public boolean

Returns:

whether to trim leading and trailing blanks.
getTrim
()

Gets whether to trim leading and trailing blanks.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for this object.

pack-priv static boolean
isBlank(final String value)

public boolean

Returns:

true is comments are supported, false otherwise
isCommentMarkerSet
()

Tests whether comments are supported by this format.

private boolean

Returns:

true if the match is successful
isDelimiter
(final char
the first char (index 0).
ch0
,
final CharSequence
the match char sequence
charSeq
,
final int
where start to match
startIndex
,
final char[]
the delimiter
delimiter
,
final int
the delimiter length
delimiterLength
)

Tests whether the next characters constitute a delimiter

public boolean

Returns:

true if escapes are processed
isEscapeCharacterSet
()

Tests whether escapes are being processed.

private static boolean

Returns:

true if c is a line break character.
isLineBreak
(final char
the character to check.
c
)

Returns true if the given character is a line break character.

private static boolean

Returns:

true if c is a line break character (and not null).
isLineBreak
(final Character
the character to check, may be null.
c
)

Returns true if the given character is a line break character.

public boolean

Returns:

true if a nullString is defined
isNullStringSet
()

Tests whether a null string has been defined.

public boolean

Returns:

true if a quoteChar is defined
isQuoteCharacterSet
()

Tests whether a quoteChar has been defined.

private static boolean
isTrimChar(final char ch)

Same test as in as String#trim().

private static boolean
isTrimChar(final CharSequence charSequence, final int pos)

Same test as in as String#trim().

pack-priv <T> IOStream<T>
limit(final IOStream<T> stream)

public static CSVFormat

Returns:

a new CSV format.
newFormat
(final char
the char used for value separation, must not be a line break character
delimiter
)

Creates a new CSV format with the specified delimiter.

public CSVParser

Returns:

a parser over a stream of CSVRecords.
parse
(final Reader
the input stream
reader
)

Parses the specified content.

public CSVPrinter

Returns:

a printer to System#out.
printer
()

Prints to the System#out.

public synchronized void
println(final Appendable
where to write
appendable
)

Outputs the trailing delimiter (if set) followed by the record separator (if set).

public synchronized void
printRecord(final Appendable
where to write.
appendable
,
final Object...
values to output.
values
)

Prints the given values to out as a single record of delimiter-separated values followed by the record separator.

private void
printWithEscapes(final CharSequence charSeq, final Appendable appendable)

private void
printWithEscapes(final Reader reader, final Appendable appendable)

private void
printWithQuotes(final Object object, final CharSequence charSeq, final Appendable out, final boolean newRecord)

private void
printWithQuotes(final Reader
What to print
reader
,
final Appendable
Where to print it
appendable
)

Always use quotes unless QuoteMode is NONE, so we do not have to look ahead.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

pack-priv static String[]
toStringArray(final Object[] values)

pack-priv static CharSequence
trim(final CharSequence charSequence)

pack-priv String
trim(final String value)

pack-priv boolean
pack-priv boolean
useRow(final long rowNum)

private void
validate()

Verifies the validity and consistency of the attributes, and throws an IllegalArgumentException if necessary.

public static CSVFormat

Returns:

one of the predefined formats
valueOf
(final String
name
format
)

Gets one of the predefined formats from CSVFormat.Predefined.

public CSVFormat

Returns:

a new CSVFormat that allows duplicate header names
withAllowDuplicateHeaderNames
()

Builds a new CSVFormat that allows duplicate header names.

public CSVFormat

Returns:

a new CSVFormat with duplicate header names behavior set to the given value.
withAllowDuplicateHeaderNames
(final boolean
the duplicate header names behavior, true to allow, false to disallow.
allowDuplicateHeaderNames
)

Builds a new CSVFormat with duplicate header names behavior set to the given value.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified missing column names behavior.
withAllowMissingColumnNames
()

Builds a new CSVFormat with the missing column names behavior of the format set to true.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified missing column names behavior.
withAllowMissingColumnNames
(final boolean
the missing column names behavior, true to allow missing column names in the header line, false to cause an IllegalArgumentException to be thrown.
allowMissingColumnNames
)

Builds a new CSVFormat with the missing column names behavior of the format set to the given value.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified autoFlush setting.
withAutoFlush
(final boolean
whether to flush on close.
autoFlush
)

Builds a new CSVFormat with whether to flush on close.

public CSVFormat

Returns:

A new CSVFormat that is equal to this one but with the specified character as the comment start marker
withCommentMarker
(final char
the comment start marker
commentMarker
)

Builds a new CSVFormat with the comment start marker of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this one but with the specified character as the comment start marker
withCommentMarker
(final Character
the comment start marker, use null to disable
commentMarker
)

Builds a new CSVFormat with the comment start marker of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this with the specified character as a delimiter
withDelimiter
(final char
the delimiter character
delimiter
)

Builds a new CSVFormat with the delimiter of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified character as the escape character
withEscape
(final char
the escape character
escape
)
Deprecated Use Builder#setEscape(char)

Builds a new CSVFormat with the escape character of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified character as the escape character
withEscape
(final Character
the escape character, use null to disable
escape
)

Builds a new CSVFormat with the escape character of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but using the first record as header.
withFirstRecordAsHeader
()
Deprecated Use Builder#setHeader().

Builds a new CSVFormat using the first record as header.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified header
withHeader
(final Class<? extends Enum<?>>
the enum defining the header, null if disabled, empty if parsed automatically, user specified otherwise.
headerEnum
)
Deprecated Use Builder#setHeader(Class)

Builds a new CSVFormat with the header of the format defined by the enum class.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified header
withHeader
(final ResultSet
the resultSet for the header, null if disabled, empty if parsed automatically, user-specified otherwise.
resultSet
)

Builds a new CSVFormat with the header of the format set from the result set metadata.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified header
withHeader
(final ResultSetMetaData
the metaData for the header, null if disabled, empty if parsed automatically, user specified otherwise.
resultSetMetaData
)

Builds a new CSVFormat with the header of the format set from the result set metadata.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified header
withHeader
(final String...
the header, null if disabled, empty if parsed automatically, user-specified otherwise.
header
)

Builds a new CSVFormat with the header of the format set to the given values.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified header
withHeaderComments
(final Object...
the headerComments which will be printed by the Printer before the actual CSV data.
headerComments
)

Builds a new CSVFormat with the header comments of the format set to the given values.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified empty line skipping behavior.
withIgnoreEmptyLines
()

Builds a new CSVFormat with the empty line skipping behavior of the format set to true.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified empty line skipping behavior.
withIgnoreEmptyLines
(final boolean
the empty line skipping behavior, true to ignore the empty lines between the records, false to translate empty lines to empty records.
ignoreEmptyLines
)

Builds a new CSVFormat with the empty line skipping behavior of the format set to the given value.

public CSVFormat

Returns:

A new CSVFormat that will ignore the new case header name behavior.
withIgnoreHeaderCase
()

Builds a new CSVFormat with the header ignore case behavior set to true.

public CSVFormat

Returns:

A new CSVFormat that will ignore case header name if specified as true
withIgnoreHeaderCase
(final boolean
the case mapping behavior, true to access name/values, false to leave the mapping as is.
ignoreHeaderCase
)

Builds a new CSVFormat with whether header names should be accessed ignoring case.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified parser trimming behavior.
withIgnoreSurroundingSpaces
()

Builds a new CSVFormat with the parser trimming behavior of the format set to true.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified trimming behavior.
withIgnoreSurroundingSpaces
(final boolean
the parser trimming behavior, true to remove the surrounding spaces, false to leave the spaces as is.
ignoreSurroundingSpaces
)

Builds a new CSVFormat with the parser trimming behavior of the format set to the given value.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified null conversion string.
withNullString
(final String
the String to convert to and from null. No substitution occurs if null
nullString
)

Builds a new CSVFormat with conversions to and from null for strings on input and output.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified character as quoteChar
withQuote
(final char
the quote character
quoteChar
)
Deprecated Use Builder#setQuote(char)

Builds a new CSVFormat with the quoteChar of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified character as quoteChar
withQuote
(final Character
the quote character, use null to disable.
quoteChar
)

Builds a new CSVFormat with the quoteChar of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified quote policy
withQuoteMode
(final QuoteMode
the quote policy to use for output.
quoteMode
)

Builds a new CSVFormat with the output quote policy of the format set to the specified value.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified output record separator
withRecordSeparator
(final char
the record separator to use for output.
recordSeparator
)

Builds a new CSVFormat with the record separator of the format set to the specified character.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified output record separator
withRecordSeparator
(final String
the record separator to use for output.
recordSeparator
)

Builds a new CSVFormat with the record separator of the format set to the specified String.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified skipHeaderRecord setting.
withSkipHeaderRecord
()

Builds a new CSVFormat with skipping the header record set to true.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified skipHeaderRecord setting.
withSkipHeaderRecord
(final boolean
whether to skip the header record.
skipHeaderRecord
)

Builds a new CSVFormat with whether to skip the header record.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the operating system's line separator string.
withSystemRecordSeparator
()

Builds a new CSVFormat with the record separator of the format set to the operating system's line separator string, typically CR+LF on Windows and LF on Linux.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the trailing delimiter setting.
withTrailingDelimiter
()

Builds a new CSVFormat to add a trailing delimiter.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified trailing delimiter setting.
withTrailingDelimiter
(final boolean
whether to add a trailing delimiter.
trailingDelimiter
)

Builds a new CSVFormat with whether to add a trailing delimiter.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the trim setting on.
withTrim
()
Deprecated Use Builder#setTrim(true)

Builds a new CSVFormat to trim leading and trailing blanks.

public CSVFormat

Returns:

A new CSVFormat that is equal to this but with the specified trim setting.
withTrim
(final boolean
whether to trim leading and trailing blanks.
trim
)
Deprecated Use Builder#setTrim(boolean)

Builds a new CSVFormat with whether to trim leading and trailing blanks.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait