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

public final Class CSVPrinter

extends Object
implements Flushable, Closeable
Class Inheritance
All Implemented Interfaces
java.io.Closeable, java.lang.AutoCloseable, java.io.Flushable
Static Imports
org.apache.commons.csv.Constants.CR, .Constants.LF, .Constants.SP

Prints values in a CSV format.

Values can be appended to the output by calling the print(Object) method. Values are printed according to String#valueOf(Object). To complete a record the println() method has to be called. Comments can be appended by calling printComment(String). However a comment will only be written to the output if the CSVFormat supports comments.

The printer also supports appending a complete record at once by calling printRecord(Object...) or printRecord(Iterable). Furthermore printRecords(Object...), printRecords(Iterable) and printRecords(ResultSet) methods can be used to print several records at once.

Example:

try (CSVPrinter printer = new CSVPrinter(new FileWriter("csv.txt"), CSVFormat.EXCEL)) {
    printer.printRecord("id", "userName", "firstName", "lastName", "birthday");
    printer.printRecord(1, "john73", "John", "Doe", LocalDate.of(1973, 9, 15));
    printer.println();
    printer.printRecord(2, "mary", "Mary", "Meyer", LocalDate.of(1985, 3, 29));
} catch (IOException ex) {
    ex.printStackTrace();
}

This code will write the following to csv.txt:

id,userName,firstName,lastName,birthday
1,john73,John,Doe,1973-09-15

2,mary,Mary,Meyer,1985-03-29

Field Summary

Modifier and TypeField and Description
private final Appendable
appendable

The place that the values get written.

private final CSVFormat
private boolean
newRecord

True if we just began a new record.

private long

Constructor Summary

AccessConstructor and Description
public
CSVPrinter(final Appendable
stream to which to print. Must not be null.
appendable
,
final CSVFormat
the CSV format. Must not be null.
format
)

Creates a printer that will print values to the given stream following the CSVFormat.

Method Summary

Modifier and TypeMethod and Description
public void
close()

Implements java.io.Closeable.close.

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

public void
close(final boolean
whether to flush before the actual close.
flush
)

Closes the underlying stream with an optional flush first.

private synchronized void
endOfRecord()

Prints the record separator and increments the record count.

public void
flush()

Implements java.io.Flushable.flush.

Flushes the underlying stream.

public Appendable

Returns:

the target Appendable.
getOut
()

Gets the target Appendable.

public long

Returns:

the record count, this does not include comments or headers.
getRecordCount
()

Gets the record count printed, this does not include comments or headers.

public synchronized void
printComment(final String
the comment to output
comment
)

Prints a comment on a new line among the delimiter-separated values.

public synchronized void
printHeaders(final ResultSet
The ResultSet to query for metadata.
resultSet
)

Prints headers for a result set based on its metadata.

public synchronized void
println()

Prints the record separator.

public synchronized void
printRecord(final Iterable<?>
values to output.
values
)

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

public void
printRecord(final Object...
values to output.
values
)

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

public synchronized void
printRecord(final Stream<?>
values to output.
values
)

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

private void
private void
printRecords(final IOStream<?> stream)

public void
printRecords(final Iterable<?>
the values to print.
values
)

Prints all the objects in the given Iterable handling nested collections/arrays as records.

public void
printRecords(final Object...
the values to print.
values
)

Prints all the objects in the given array handling nested collections/arrays as records.

public void
printRecords(final ResultSet
The values to print.
resultSet
)

Prints all the objects in the given JDBC result set.

public void
printRecords(final ResultSet
source of row data.
resultSet
,
final boolean
whether to print headers.
printHeader
)

Prints all the objects with metadata in the given JDBC result set based on the header boolean.

public void
printRecords(final Stream<?>
the values to print.
values
)

Prints all the objects in the given Stream handling nested collections/arrays as records.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

appendableback to summary
private final Appendable appendable

The place that the values get written.

formatback to summary
private final CSVFormat format
newRecordback to summary
private boolean newRecord

True if we just began a new record.

recordCountback to summary
private long recordCount

Constructor Detail

CSVPrinterback to summary
public CSVPrinter(final Appendable appendable, final CSVFormat format) throws IOException

Creates a printer that will print values to the given stream following the CSVFormat.

Currently, only a pure encapsulation format or a pure escaping format is supported. Hybrid formats (encapsulation and escaping with a different character) are not supported.

Parameters
appendable:Appendable

stream to which to print. Must not be null.

format:CSVFormat

the CSV format. Must not be null.

Exceptions
IOException:
thrown if the optional header cannot be printed.
IllegalArgumentException:
thrown if the parameters of the format are inconsistent.
NullPointerException:
thrown if either parameters are null.

Method Detail

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
closeback to summary
public void close(final boolean flush) throws IOException

Closes the underlying stream with an optional flush first.

Parameters
flush:boolean

whether to flush before the actual close.

Exceptions
IOException:
If an I/O error occurs
Since
1.6
See Also
CSVFormat#getAutoFlush()
endOfRecordback to summary
private synchronized void endOfRecord() throws IOException

Prints the record separator and increments the record count.

Exceptions
IOException:
If an I/O error occurs
flushback to summary
public void flush() throws IOException

Implements java.io.Flushable.flush.

Flushes the underlying stream.

Annotations
@Override
Exceptions
IOException:
If an I/O error occurs
getOutback to summary
public Appendable getOut()

Gets the target Appendable.

Returns:Appendable

the target Appendable.

getRecordCountback to summary
public long getRecordCount()

Gets the record count printed, this does not include comments or headers.

Returns:long

the record count, this does not include comments or headers.

Since
1.13.0
printCommentback to summary
public synchronized void printComment(final String comment) throws IOException

Prints a comment on a new line among the delimiter-separated values.

Comments will always begin on a new line and occupy at least one full line. The character specified to start comments and a space will be inserted at the beginning of each new line in the comment.

If comments are disabled in the current CSV format this method does nothing.

This method detects line breaks inside the comment string and inserts CSVFormat#getRecordSeparator() to start a new line of the comment. Note that this might produce unexpected results for formats that do not use line breaks as record separators.

Parameters
comment:String

the comment to output

Exceptions
IOException:
If an I/O error occurs
printHeadersback to summary
public synchronized void printHeaders(final ResultSet resultSet) throws IOException, SQLException

Prints headers for a result set based on its metadata.

Parameters
resultSet:ResultSet

The ResultSet to query for metadata.

Exceptions
IOException:
If an I/O error occurs.
SQLException:
If a database access error occurs or this method is called on a closed result set.
Since
1.9.0
printlnback to summary
public synchronized void println() throws IOException

Prints the record separator.

Exceptions
IOException:
If an I/O error occurs
printRecordback to summary
public synchronized void printRecord(final Iterable<?> values) throws IOException

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

The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record separator to the output after printing the record, so there is no need to call println().

Parameters
values:Iterable<?>

values to output.

Annotations
@SuppressWarnings:resource
Exceptions
IOException:
If an I/O error occurs
printRecordback to summary
public void printRecord(final Object... values) throws IOException

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

The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record separator to the output after printing the record, so there is no need to call println().

Parameters
values:Object[]

values to output.

Exceptions
IOException:
If an I/O error occurs
printRecordback to summary
public synchronized void printRecord(final Stream<?> values) throws IOException

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

The values will be quoted if needed. Quotes and newLine characters will be escaped. This method adds the record separator to the output after printing the record, so there is no need to call println().

Parameters
values:Stream<?>

values to output.

Annotations
@SuppressWarnings:resource
Exceptions
IOException:
If an I/O error occurs
Since
1.10.0
printRecordObjectback to summary
private void printRecordObject(final Object value) throws IOException
printRecordsback to summary
private void printRecords(final IOStream<?> stream) throws IOException
Annotations
@SuppressWarnings:resource
printRecordsback to summary
public void printRecords(final Iterable<?> values) throws IOException

Prints all the objects in the given Iterable handling nested collections/arrays as records.

If the given Iterable only contains simple objects, this method will print a single record like printRecord(Iterable). If the given Iterable contains nested collections/arrays those nested elements will each be printed as records using printRecord(Object...).

Given the following data structure:

List<String[]> data = new ArrayList<>();
data.add(new String[]{ "A", "B", "C" });
data.add(new String[]{ "1", "2", "3" });
data.add(new String[]{ "A1", "B2", "C3" });

Calling this method will print:

A, B, C
1, 2, 3
A1, B2, C3

Parameters
values:Iterable<?>

the values to print.

Annotations
@SuppressWarnings:resource
Exceptions
IOException:
If an I/O error occurs
printRecordsback to summary
public void printRecords(final Object... values) throws IOException

Prints all the objects in the given array handling nested collections/arrays as records.

If the given array only contains simple objects, this method will print a single record like printRecord(Object...). If the given collections contain nested collections or arrays, those nested elements will each be printed as records using printRecord(Object...).

Given the following data structure:

String[][] data = new String[3][]
data[0] = String[]{ "A", "B", "C" };
data[1] = new String[]{ "1", "2", "3" };
data[2] = new String[]{ "A1", "B2", "C3" };

Calling this method will print:

A, B, C
1, 2, 3
A1, B2, C3

Parameters
values:Object[]

the values to print.

Exceptions
IOException:
If an I/O error occurs
printRecordsback to summary
public void printRecords(final ResultSet resultSet) throws SQLException, IOException

Prints all the objects in the given JDBC result set.

You can use CSVFormat.Builder#setMaxRows(long) to limit how many rows a result set produces. This is most useful when you cannot limit rows through Statement#setLargeMaxRows(long) or Statement#setMaxRows(int).

Parameters
resultSet:ResultSet

The values to print.

Exceptions
SQLException:
Thrown when a database access error occurs.
IOException:
If an I/O error occurs.
printRecordsback to summary
public void printRecords(final ResultSet resultSet, final boolean printHeader) throws SQLException, IOException

Prints all the objects with metadata in the given JDBC result set based on the header boolean.

You can use CSVFormat.Builder#setMaxRows(long) to limit how many rows a result set produces. This is most useful when you cannot limit rows through Statement#setLargeMaxRows(long) or Statement#setMaxRows(int).

Parameters
resultSet:ResultSet

source of row data.

printHeader:boolean

whether to print headers.

Exceptions
SQLException:
if a database access error occurs
IOException:
If an I/O error occurs
Since
1.9.0
printRecordsback to summary
public void printRecords(final Stream<?> values) throws IOException

Prints all the objects in the given Stream handling nested collections/arrays as records.

If the given Stream only contains simple objects, this method will print a single record like printRecord(Iterable). If the given Stream contains nested collections/arrays those nested elements will each be printed as records using printRecord(Object...).

Given the following data structure:

List<String[]> data = new ArrayList<>();
data.add(new String[]{ "A", "B", "C" });
data.add(new String[]{ "1", "2", "3" });
data.add(new String[]{ "A1", "B2", "C3" });
Stream<String[]> stream = data.stream();

Calling this method will print:

A, B, C
1, 2, 3
A1, B2, C3

Parameters
values:Stream<?>

the values to print.

Annotations
@SuppressWarnings:resource
Exceptions
IOException:
If an I/O error occurs
Since
1.10.0