Top Description Inners Fields Constructors Methods
de.siegmar.fastcsv.writer

public final Class CsvWriter

extends Object
implements Closeable, Flushable
Class Inheritance
All Implemented Interfaces
java.io.Flushable, java.io.Closeable, java.lang.AutoCloseable
Annotations
@SuppressWarnings:checkstyle:NPathComplexity, checkstyle:CyclomaticComplexity
Static Imports
de.siegmar.fastcsv.util.Util.CR, .Util.LF

This is the main class for writing CSV data.

Example use:

try (CsvWriter csv = CsvWriter.builder().build(file)) { csv.writeRecord("Hello", "world"); }
try (CsvWriter csv = CsvWriter.builder().build(file)) {
    csv.writeRecord("Hello", "world");
}

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
CsvWriter.CsvWriterBuilder

This builder is used to create configured instances of CsvWriter.

public class
CsvWriter.CsvWriterRecord

This class is used to write a record field by field.

Field Summary

Modifier and TypeField and Description
private final char
private int
private final char[]
private final char
private final LineDelimiter
private final char[]
private boolean
private final char
private final QuoteStrategy
private final Writable

Constructor Summary

AccessConstructor and Description
pack-priv
CsvWriter(final Writable writer, final char fieldSeparator, final char quoteCharacter, final char commentCharacter, final QuoteStrategy quoteStrategy, final LineDelimiter lineDelimiter)

Method Summary

Modifier and TypeMethod and Description
public static CsvWriter.CsvWriterBuilder

Returns:

CsvWriterBuilder instance with default settings.
builder
()

Creates a CsvWriterBuilder instance used to configure and create instances of this class.

public void
close()

Implements java.io.Closeable.close.

Closes this stream and releases any system resources associated with it.

private boolean
containsControlCharacter(final String value, final int fieldIdx, final int length)

private CsvWriter
public void
flush()

Implements java.io.Flushable.flush.

Flushes this stream by writing any buffered output to the underlying stream.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

private void
public CsvWriter

Returns:

This CsvWriter.
writeComment
(final String
the comment to write. The comment character (configured by CsvWriterBuilder#commentCharacter(char)) is automatically prepended. Empty or null values results in a line only consisting of the comment character. If the argument comment contains line break characters (CR, LF), multiple comment lines will be written, terminated with the line break character configured by CsvWriterBuilder#lineDelimiter(LineDelimiter).
comment
)

Writes a comment line and new line character(s) at the end.

private void
private static void
writeEscaped(final Writable w, final String value, final char quoteChar)

private void
writeFragment(final String comment, final int i, final int startPos)

private void
writeInternal(final String value, final int fieldIdx)

public CsvWriter

Returns:

This CsvWriter.
writeRecord
(final Iterable<String>
the fields to write (null values are handled as empty strings, if not configured otherwise (QuoteStrategies#EMPTY)).
values
)

Writes a complete line - one or more fields and new line character(s) at the end.

public CsvWriter

Returns:

This CsvWriter.
writeRecord
(final String...
the fields to write (null values are handled as empty strings, if not configured otherwise (QuoteStrategies#EMPTY))
values
)

Writes a complete line - one or more fields and new line character(s) at the end.

public CsvWriter.CsvWriterRecord

Returns:

CsvWriterRecord instance to write fields to.
writeRecord
()

Starts a new record.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

commentCharacterback to summary
private final char commentCharacter
currentLineNoback to summary
private int currentLineNo
emptyFieldValueback to summary
private final char[] emptyFieldValue
fieldSeparatorback to summary
private final char fieldSeparator
lineDelimiterback to summary
private final LineDelimiter lineDelimiter
lineDelimiterCharsback to summary
private final char[] lineDelimiterChars
openRecordWriterback to summary
private boolean openRecordWriter
quoteCharacterback to summary
private final char quoteCharacter
quoteStrategyback to summary
private final QuoteStrategy quoteStrategy
writerback to summary
private final Writable writer

Constructor Detail

CsvWriterback to summary
pack-priv CsvWriter(final Writable writer, final char fieldSeparator, final char quoteCharacter, final char commentCharacter, final QuoteStrategy quoteStrategy, final LineDelimiter lineDelimiter)
Annotations
@SuppressWarnings:checkstyle:ParameterNumber

Method Detail

builderback to summary
public static CsvWriter.CsvWriterBuilder builder()

Creates a CsvWriterBuilder instance used to configure and create instances of this class.

Returns:CsvWriter.CsvWriterBuilder

CsvWriterBuilder instance with default settings.

closeback to summary
public void close() throws IOException

Implements java.io.Closeable.close.

Doc from java.io.Closeable.close.

Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.

As noted in AutoCloseable#close(), cases where the close may fail require careful attention. It is strongly advised to relinquish the underlying resources and to internally mark the Closeable as closed, prior to throwing the IOException.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs
containsControlCharacterback to summary
private boolean containsControlCharacter(final String value, final int fieldIdx, final int length)
Annotations
@SuppressWarnings:checkstyle:BooleanExpressionComplexity, checkstyle:ReturnCount, checkstyle:MagicNumber, PMD.AvoidLiteralsInIfCondition
endRecordback to summary
private CsvWriter endRecord() throws IOException
flushback to summary
public void flush() throws IOException

Implements java.io.Flushable.flush.

Doc from java.io.Flushable.flush.

Flushes this stream by writing any buffered output to the underlying stream.

Annotations
@Override
Exceptions
IOException:
If an I/O error occurs
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Annotations
@Override
validateNoOpenRecordback to summary
private void validateNoOpenRecord()
writeCommentback to summary
public CsvWriter writeComment(final String comment)

Writes a comment line and new line character(s) at the end.

Note that comments are not part of the CSV standard and may not be supported by all readers.

Parameters
comment:String

the comment to write. The comment character (configured by CsvWriterBuilder#commentCharacter(char)) is automatically prepended. Empty or null values results in a line only consisting of the comment character. If the argument comment contains line break characters (CR, LF), multiple comment lines will be written, terminated with the line break character configured by CsvWriterBuilder#lineDelimiter(LineDelimiter).

Returns:CsvWriter

This CsvWriter.

Exceptions
UncheckedIOException:
if a write-error occurs
IllegalStateException:
if a record is already started (by calling writeRecord()) and not ended
writeCommentInternalback to summary
private void writeCommentInternal(final String comment) throws IOException
writeEscapedback to summary
private static void writeEscaped(final Writable w, final String value, final char quoteChar) throws IOException
writeFragmentback to summary
private void writeFragment(final String comment, final int i, final int startPos) throws IOException
writeInternalback to summary
private void writeInternal(final String value, final int fieldIdx) throws IOException
Annotations
@SuppressWarnings:checkstyle:BooleanExpressionComplexity
writeRecordback to summary
public CsvWriter writeRecord(final Iterable<String> values)

Writes a complete line - one or more fields and new line character(s) at the end.

Parameters
values:Iterable<String>

the fields to write (null values are handled as empty strings, if not configured otherwise (QuoteStrategies#EMPTY)).

Returns:CsvWriter

This CsvWriter.

Exceptions
UncheckedIOException:
if a write-error occurs
IllegalStateException:
if a record is already started (by calling writeRecord()) and not ended
See Also
writeRecord(String...)
writeRecordback to summary
public CsvWriter writeRecord(final String... values)

Writes a complete line - one or more fields and new line character(s) at the end.

Parameters
values:String[]

the fields to write (null values are handled as empty strings, if not configured otherwise (QuoteStrategies#EMPTY))

Returns:CsvWriter

This CsvWriter.

Exceptions
UncheckedIOException:
if a write-error occurs
IllegalStateException:
if a record is already started (by calling writeRecord()) and not ended
See Also
writeRecord(Iterable)
writeRecordback to summary
public CsvWriter.CsvWriterRecord writeRecord()

Starts a new record.

This method is used to write a record field by field. The record is ended by calling endRecord().

Returns:CsvWriter.CsvWriterRecord

CsvWriterRecord instance to write fields to.

Exceptions
IllegalStateException:
if a record is already started
See Also
writeRecord(String...), writeRecord(Iterable)
de.siegmar.fastcsv.writer back to summary

public final Class CsvWriter.CsvWriterBuilder

extends Object
Class Inheritance
Annotations
@SuppressWarnings:checkstyle:HiddenField, PMD.AvoidFieldNameMatchingMethodName

This builder is used to create configured instances of CsvWriter. The default configuration of this class adheres with RFC 4180.

Field Summary

Modifier and TypeField and Description
private boolean
private int
private char
private static final int
private char
private LineDelimiter
private char
private QuoteStrategy

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
autoFlush
(final boolean
whether the data should be flushed after each record write operation.
autoFlush
)

Configures whether data should be flushed after each record write operation.

public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
bufferSize
(final int
the buffer size to be used (must be ≥ 0).
bufferSize
)

Configures the size of the internal buffer.

public CsvWriter

Returns:

a new CsvWriter instance - never null. Remember to close it!
build
(final OutputStream
the OutputStream to write CSV data to.
outputStream
)

Constructs a CsvWriter for the specified OutputStream.

public CsvWriter

Returns:

a new CsvWriter instance - never null. Remember to close it!
build
(final OutputStream
the OutputStream to write CSV data to.
outputStream
,
final Charset
the character set to be used for writing data to the output stream.
charset
)

Constructs a CsvWriter for the specified OutputStream and character set.

public CsvWriter

Returns:

a new CsvWriter instance - never null. Remember to close it!
build
(final Writer
the Writer to use for writing CSV data.
writer
)

Constructs a CsvWriter for the specified Writer.

public CsvWriter

Returns:

a new CsvWriter instance - never null. Remember to close it!
build
(final Path
the file to write data to.
file
,
final OpenOption...
options specifying how the file is opened. See Files#newOutputStream(Path, OpenOption...) for defaults.
openOptions
)

Constructs a CsvWriter for the specified Path.

public CsvWriter

Returns:

a new CsvWriter instance - never null. Remember to close it!
build
(final Path
the file to write data to.
file
,
final Charset
the character set to be used for writing data to the file.
charset
,
final OpenOption...
options specifying how the file is opened. See Files#newOutputStream(Path, OpenOption...) for defaults.
openOptions
)

Constructs a CsvWriter for the specified Path.

public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
commentCharacter
(final char
the character for prepending commented lines.
commentCharacter
)

Sets the character used to prepend commented lines – default: # (hash/number).

private CsvWriter
csvWriter(final Writer writer, final int bufferSize, final boolean autoFlushWriter)

public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
fieldSeparator
(final char
the field separator character.
fieldSeparator
)

Sets the character that is used to separate fields – default: , (comma).

public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
lineDelimiter
(final LineDelimiter
the line delimiter to be used; must not be null.
lineDelimiter
)

Sets the delimiter used to separate lines (default: LineDelimiter#CRLF).

public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
quoteCharacter
(final char
the character for enclosing fields.
quoteCharacter
)

Sets the character used to quote values – default: " (double quote).

public CsvWriter.CsvWriterBuilder

Returns:

This updated object, allowing additional method calls to be chained together.
quoteStrategy
(final QuoteStrategy
the strategy when fields should be enclosed using the quoteCharacter, even if not strictly required; must not be null.
quoteStrategy
)

Sets the strategy that defines when optional quoting has to be performed (default: QuoteStrategies#REQUIRED).

public CsvWriter

Returns:

a new CsvWriter instance - never null. Calls to CsvWriter#close() are ignored, standard out remains open.
toConsole
()

Convenience method to write to the console (standard output).

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

private static Writable
wrapWriter(final Writer writer, final int bufferSize, final boolean autoFlushWriter)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

autoFlushback to summary
private boolean autoFlush
bufferSizeback to summary
private int bufferSize
commentCharacterback to summary
private char commentCharacter
DEFAULT_BUFFER_SIZEback to summary
private static final int DEFAULT_BUFFER_SIZE
fieldSeparatorback to summary
private char fieldSeparator
lineDelimiterback to summary
private LineDelimiter lineDelimiter
quoteCharacterback to summary
private char quoteCharacter
quoteStrategyback to summary
private QuoteStrategy quoteStrategy

Constructor Detail

CsvWriterBuilderback to summary
pack-priv CsvWriterBuilder()

Method Detail

autoFlushback to summary
public CsvWriter.CsvWriterBuilder autoFlush(final boolean autoFlush)

Configures whether data should be flushed after each record write operation.

Obviously this comes with drastic performance implications but can be useful for debugging purposes.

This setting is ignored when using toConsole() as console output is always flushed.

Parameters
autoFlush:boolean

whether the data should be flushed after each record write operation.

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

bufferSizeback to summary
public CsvWriter.CsvWriterBuilder bufferSize(final int bufferSize)

Configures the size of the internal buffer.

The default buffer size of 8,192 bytes usually does not need to be altered. One use-case is if you need many instances of a CsvWriter and need to optimize for instantiation time and memory footprint.

A buffer size of 0 disables the buffer.

This setting is ignored when using toConsole() as console output is unbuffered.

Parameters
bufferSize:int

the buffer size to be used (must be ≥ 0).

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

buildback to summary
public CsvWriter build(final OutputStream outputStream)

Constructs a CsvWriter for the specified OutputStream.

See build(OutputStream, Charset) for details. This is just a convenience method for calling it with charset set to StandardCharsets#UTF_8.

Parameters
outputStream:OutputStream

the OutputStream to write CSV data to.

Returns:CsvWriter

a new CsvWriter instance - never null. Remember to close it!

Exceptions
NullPointerException:
if outputStream is null
See Also
build(OutputStream, Charset)
buildback to summary
public CsvWriter build(final OutputStream outputStream, final Charset charset)

Constructs a CsvWriter for the specified OutputStream and character set.

This build method wraps the given outputStream with an OutputStreamWriter. Both this library's internal buffer and the used OutputStreamWriter cause deferred writes to the underlying stream. You typically do not need to wrap the given outputStream in a java.io.BufferedOutputStream. This ensures good performance but also means that you must call flush() or close() to ensure that all data is written to the underlying outputStream!

Use build(Path, Charset, OpenOption...) for optimal performance when writing files!

Parameters
outputStream:OutputStream

the OutputStream to write CSV data to.

charset:Charset

the character set to be used for writing data to the output stream.

Returns:CsvWriter

a new CsvWriter instance - never null. Remember to close it!

Exceptions
NullPointerException:
if outputStream or charset is null
See Also
build(OutputStream)
buildback to summary
public CsvWriter build(final Writer writer)

Constructs a CsvWriter for the specified Writer.

This library uses built-in buffering, unless bufferSize(int) is used to disable it. You typically do not need to wrap the given writer in an java.io.BufferedWriter. This ensures good performance but also means that you must call flush() or close() to ensure that all data is written to the underlying writer!

Use build(Path, Charset, OpenOption...) for optimal performance when writing files!

Parameters
writer:Writer

the Writer to use for writing CSV data.

Returns:CsvWriter

a new CsvWriter instance - never null. Remember to close it!

Exceptions
NullPointerException:
if writer is null
buildback to summary
public CsvWriter build(final Path file, final OpenOption... openOptions) throws IOException

Constructs a CsvWriter for the specified Path.

See build(Path, Charset, OpenOption...) for details. This is just a convenience method for calling it with charset set to StandardCharsets#UTF_8.

Parameters
file:Path

the file to write data to.

openOptions:OpenOption[]

options specifying how the file is opened. See Files#newOutputStream(Path, OpenOption...) for defaults.

Returns:CsvWriter

a new CsvWriter instance - never null. Remember to close it!

Exceptions
IOException:
if a write-error occurs
NullPointerException:
if file or charset is null
buildback to summary
public CsvWriter build(final Path file, final Charset charset, final OpenOption... openOptions) throws IOException

Constructs a CsvWriter for the specified Path.

Parameters
file:Path

the file to write data to.

charset:Charset

the character set to be used for writing data to the file.

openOptions:OpenOption[]

options specifying how the file is opened. See Files#newOutputStream(Path, OpenOption...) for defaults.

Returns:CsvWriter

a new CsvWriter instance - never null. Remember to close it!

Exceptions
IOException:
if a write-error occurs
NullPointerException:
if file or charset is null
commentCharacterback to summary
public CsvWriter.CsvWriterBuilder commentCharacter(final char commentCharacter)

Sets the character used to prepend commented lines – default: # (hash/number).

Parameters
commentCharacter:char

the character for prepending commented lines.

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

csvWriterback to summary
private CsvWriter csvWriter(final Writer writer, final int bufferSize, final boolean autoFlushWriter)
fieldSeparatorback to summary
public CsvWriter.CsvWriterBuilder fieldSeparator(final char fieldSeparator)

Sets the character that is used to separate fields – default: , (comma).

Parameters
fieldSeparator:char

the field separator character.

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

lineDelimiterback to summary
public CsvWriter.CsvWriterBuilder lineDelimiter(final LineDelimiter lineDelimiter)

Sets the delimiter used to separate lines (default: LineDelimiter#CRLF).

Parameters
lineDelimiter:LineDelimiter

the line delimiter to be used; must not be null.

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

Exceptions
NullPointerException:
if lineDelimiter is null
quoteCharacterback to summary
public CsvWriter.CsvWriterBuilder quoteCharacter(final char quoteCharacter)

Sets the character used to quote values – default: " (double quote).

Be aware that using characters other than the default double quote character goes against the RFC 4180 standard.

Parameters
quoteCharacter:char

the character for enclosing fields.

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

quoteStrategyback to summary
public CsvWriter.CsvWriterBuilder quoteStrategy(final QuoteStrategy quoteStrategy)

Sets the strategy that defines when optional quoting has to be performed (default: QuoteStrategies#REQUIRED).

Parameters
quoteStrategy:QuoteStrategy

the strategy when fields should be enclosed using the quoteCharacter, even if not strictly required; must not be null.

Returns:CsvWriter.CsvWriterBuilder

This updated object, allowing additional method calls to be chained together.

Exceptions
NullPointerException:
if quoteStrategy is null
See Also
QuoteStrategies
toConsoleback to summary
public CsvWriter toConsole()

Convenience method to write to the console (standard output).

Settings bufferSize(int) and autoFlush(boolean) are ignored. Data is directly written to standard output and flushed after each record.

Example use:

CsvWriter.builder().toConsole() .writeRecord("Hello", "world");
CsvWriter.builder().toConsole()
    .writeRecord("Hello", "world");
Returns:CsvWriter

a new CsvWriter instance - never null. Calls to CsvWriter#close() are ignored, standard out remains open.

Annotations
@SuppressWarnings:checkstyle:RegexpMultiline
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Annotations
@Override
wrapWriterback to summary
private static Writable wrapWriter(final Writer writer, final int bufferSize, final boolean autoFlushWriter)
de.siegmar.fastcsv.writer back to summary

public final Class CsvWriter.CsvWriterRecord

extends Object
Class Inheritance

This class is used to write a record field by field.

The record is ended by calling endRecord().

Field Summary

Modifier and TypeField and Description
private int

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public CsvWriter

Returns:

the enclosing CsvWriter instance
endRecord
()

Ends the current record.

public CsvWriter.CsvWriterRecord

Returns:

this CsvWriterRecord instance
writeField
(final String
the field value
value
)

Writes a field to the current record.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

fieldIdxback to summary
private int fieldIdx

Constructor Detail

CsvWriterRecordback to summary
private CsvWriterRecord()

Method Detail

endRecordback to summary
public CsvWriter endRecord()

Ends the current record.

Returns:CsvWriter

the enclosing CsvWriter instance

Exceptions
UncheckedIOException:
if a write-error occurs
writeFieldback to summary
public CsvWriter.CsvWriterRecord writeField(final String value)

Writes a field to the current record.

Parameters
value:String

the field value

Returns:CsvWriter.CsvWriterRecord

this CsvWriterRecord instance

Exceptions
UncheckedIOException:
if a write-error occurs