Class CSVPrinter
- java.lang.Object
-
- org.apache.commons.csv.CSVPrinter
-
- All Implemented Interfaces:
java.io.Closeable,java.io.Flushable,java.lang.AutoCloseable
public final class CSVPrinter extends java.lang.Object implements java.io.Flushable, java.io.CloseablePrints values in aCSV format.Values can be appended to the output by calling the
print(Object)method. Values are printed according toString.valueOf(Object). To complete a record theprintln()method has to be called. Comments can be appended by callingprintComment(String). However a comment will only be written to the output if theCSVFormatsupports comments.The printer also supports appending a complete record at once by calling
printRecord(Object...)orprintRecord(Iterable). FurthermoreprintRecords(Object...),printRecords(Iterable)andprintRecords(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
Fields Modifier and Type Field Description private java.lang.AppendableappendableThe place that the values get written.private CSVFormatformatprivate booleannewRecordTrue if we just began a new record.private longrecordCount
-
Constructor Summary
Constructors Constructor Description CSVPrinter(java.lang.Appendable appendable, CSVFormat format)Creates a printer that will print values to the given stream following the CSVFormat.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()voidclose(boolean flush)Closes the underlying stream with an optional flush first.private voidendOfRecord()Prints the record separator and increments the record count.voidflush()Flushes the underlying stream.java.lang.AppendablegetOut()Gets the target Appendable.longgetRecordCount()Gets the record count printed, this does not include comments or headers.voidprint(java.lang.Object value)Prints the string as the next value on the line.voidprintComment(java.lang.String comment)Prints a comment on a new line among the delimiter-separated values.voidprintHeaders(java.sql.ResultSet resultSet)Prints headers for a result set based on its metadata.voidprintln()Prints the record separator.voidprintRecord(java.lang.Iterable<?> values)Prints the given values as a single record of delimiter-separated values followed by the record separator.voidprintRecord(java.lang.Object... values)Prints the given values as a single record of delimiter-separated values followed by the record separator.voidprintRecord(java.util.stream.Stream<?> values)Prints the given values as a single record of delimiter-separated values followed by the record separator.private voidprintRecordObject(java.lang.Object value)voidprintRecords(java.lang.Iterable<?> values)Prints all the objects in the givenIterablehandling nested collections/arrays as records.voidprintRecords(java.lang.Object... values)Prints all the objects in the given array handling nested collections/arrays as records.voidprintRecords(java.sql.ResultSet resultSet)Prints all the objects in the given JDBC result set.voidprintRecords(java.sql.ResultSet resultSet, boolean printHeader)Prints all the objects with metadata in the given JDBC result set based on the header boolean.voidprintRecords(java.util.stream.Stream<?> values)Prints all the objects in the givenStreamhandling nested collections/arrays as records.private voidprintRecords(org.apache.commons.io.function.IOStream<?> stream)
-
-
-
Field Detail
-
appendable
private final java.lang.Appendable appendable
The place that the values get written.
-
format
private final CSVFormat format
-
newRecord
private boolean newRecord
True if we just began a new record.
-
recordCount
private long recordCount
-
-
Constructor Detail
-
CSVPrinter
public CSVPrinter(java.lang.Appendable appendable, CSVFormat format) throws java.io.IOExceptionCreates 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- stream to which to print. Must not be null.format- the CSV format. Must not be null.- Throws:
java.io.IOException- thrown if the optional header cannot be printed.java.lang.IllegalArgumentException- thrown if the parameters of the format are inconsistent.java.lang.NullPointerException- thrown if either parameters are null.
-
-
Method Detail
-
close
public void close() throws java.io.IOException- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Throws:
java.io.IOException
-
close
public void close(boolean flush) throws java.io.IOExceptionCloses the underlying stream with an optional flush first.- Parameters:
flush- whether to flush before the actual close.- Throws:
java.io.IOException- If an I/O error occurs- Since:
- 1.6
- See Also:
CSVFormat.getAutoFlush()
-
endOfRecord
private void endOfRecord() throws java.io.IOExceptionPrints the record separator and increments the record count.- Throws:
java.io.IOException- If an I/O error occurs
-
flush
public void flush() throws java.io.IOExceptionFlushes the underlying stream.- Specified by:
flushin interfacejava.io.Flushable- Throws:
java.io.IOException- If an I/O error occurs
-
getOut
public java.lang.Appendable getOut()
Gets the target Appendable.- Returns:
- the target Appendable.
-
getRecordCount
public long getRecordCount()
Gets the record count printed, this does not include comments or headers.- Returns:
- the record count, this does not include comments or headers.
- Since:
- 1.13.0
-
print
public void print(java.lang.Object value) throws java.io.IOExceptionPrints the string as the next value on the line. The value will be escaped or encapsulated as needed.- Parameters:
value- value to be output.- Throws:
java.io.IOException- If an I/O error occurs
-
printComment
public void printComment(java.lang.String comment) throws java.io.IOExceptionPrints 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- the comment to output- Throws:
java.io.IOException- If an I/O error occurs
-
printHeaders
public void printHeaders(java.sql.ResultSet resultSet) throws java.io.IOException, java.sql.SQLExceptionPrints headers for a result set based on its metadata.- Parameters:
resultSet- The ResultSet to query for metadata.- Throws:
java.io.IOException- If an I/O error occurs.java.sql.SQLException- If a database access error occurs or this method is called on a closed result set.- Since:
- 1.9.0
-
println
public void println() throws java.io.IOExceptionPrints the record separator.- Throws:
java.io.IOException- If an I/O error occurs
-
printRecord
public void printRecord(java.lang.Iterable<?> values) throws java.io.IOExceptionPrints 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- values to output.- Throws:
java.io.IOException- If an I/O error occurs
-
printRecord
public void printRecord(java.lang.Object... values) throws java.io.IOExceptionPrints 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- values to output.- Throws:
java.io.IOException- If an I/O error occurs
-
printRecord
public void printRecord(java.util.stream.Stream<?> values) throws java.io.IOExceptionPrints 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- values to output.- Throws:
java.io.IOException- If an I/O error occurs- Since:
- 1.10.0
-
printRecordObject
private void printRecordObject(java.lang.Object value) throws java.io.IOException- Throws:
java.io.IOException
-
printRecords
private void printRecords(org.apache.commons.io.function.IOStream<?> stream) throws java.io.IOException- Throws:
java.io.IOException
-
printRecords
public void printRecords(java.lang.Iterable<?> values) throws java.io.IOExceptionPrints all the objects in the givenIterablehandling 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 usingprintRecord(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- the values to print.- Throws:
java.io.IOException- If an I/O error occurs
-
printRecords
public void printRecords(java.lang.Object... values) throws java.io.IOExceptionPrints 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 usingprintRecord(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- the values to print.- Throws:
java.io.IOException- If an I/O error occurs
-
printRecords
public void printRecords(java.sql.ResultSet resultSet) throws java.sql.SQLException, java.io.IOExceptionPrints 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 throughStatement.setLargeMaxRows(long)orStatement.setMaxRows(int).- Parameters:
resultSet- The values to print.- Throws:
java.io.IOException- If an I/O error occurs.java.sql.SQLException- Thrown when a database access error occurs.
-
printRecords
public void printRecords(java.sql.ResultSet resultSet, boolean printHeader) throws java.sql.SQLException, java.io.IOExceptionPrints 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 throughStatement.setLargeMaxRows(long)orStatement.setMaxRows(int).- Parameters:
resultSet- source of row data.printHeader- whether to print headers.- Throws:
java.io.IOException- If an I/O error occursjava.sql.SQLException- if a database access error occurs- Since:
- 1.9.0
-
printRecords
public void printRecords(java.util.stream.Stream<?> values) throws java.io.IOExceptionPrints all the objects in the givenStreamhandling 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 usingprintRecord(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- the values to print.- Throws:
java.io.IOException- If an I/O error occurs- Since:
- 1.10.0
-
-