Top Description Fields Constructors Methods
com.opencsv

public Class CSVReader

extends Object
implements Closeable, Iterable<String[]>
Class Inheritance
All Implemented Interfaces
java.lang.Iterable, java.io.Closeable, java.lang.AutoCloseable
Known Direct Subclasses
com.opencsv.CSVReaderHeaderAware
Imports
com.opencsv.bean.util.OrderedObject, com.opencsv.exceptions.*, com.opencsv.processor.RowProcessor, com.opencsv.stream.reader.LineReader, com.opencsv.validators.LineValidatorAggregator, .RowValidatorAggregator, org.apache.commons.lang3.ObjectUtils, .StringUtils, java.io.*, java.nio.charset.CharacterCodingException, .MalformedInputException, java.util.*, java.util.zip.ZipException

A very simple CSV reader released under a commercial-friendly license.
Author
Glen Smith

Field Summary

Modifier and TypeField and Description
protected BufferedReader
pack-priv static final int
public static final boolean
public static final int
DEFAULT_MULTILINE_LIMIT

The default limit for the number of lines in a multiline record.

public static final int
DEFAULT_SKIP_LINES

The default line to start reading.

public static final boolean
protected Locale
protected boolean
protected boolean
protected LineReader
protected long
protected boolean
private final LineValidatorAggregator
private static final int
protected int
protected ICSVParser
protected static final List<Class<? extends IOException>>
protected String[]
protected final Queue<OrderedObject<String>>
public static final int
protected long
private final RowProcessor
private final RowValidatorAggregator
protected int
protected boolean

Constructor Summary

AccessConstructor and Description
public
CSVReader(Reader
The reader to an underlying CSV source.
reader
)

Constructs CSVReader using defaults for all parameters.

pack-priv
CSVReader(Reader
The reader to an underlying CSV source
reader
,
int
The number of lines to skip before reading
line
,
ICSVParser
The parser to use to parse input
icsvParser
,
boolean
True to keep carriage returns in data read, false otherwise
keepCR
,
boolean
True to verify reader before each read, false otherwise
verifyReader
,
int
Allow the user to define the limit to the number of lines in a multiline record. Less than one means no limit.
multilineLimit
,
Locale
Set the locale for error messages. If null, the default locale is used.
errorLocale
,
LineValidatorAggregator
contains all the custom defined line validators.
lineValidatorAggregator
,
RowValidatorAggregator
contains all the custom defined row validators.
rowValidatorAggregator
,
RowProcessor
Custom row processor to run on all columns on a csv record.
rowProcessor
)

Constructs CSVReader with supplied CSVParser.

Method Summary

Modifier and TypeMethod and Description
public void
close()

Implements java.io.Closeable.close.

Closes the underlying reader.

protected String[]

Returns:

String array with union of the buffer and lastRead arrays.
combineResultsFromMultipleReads
(String[]
Previous data read for this record
buffer
,
String[]
Latest data read for this record.
lastRead
)

For multi-line records this method combines the current result with the result from previous read(s).

private String[]

Returns:

The next line of input
flexibleRead
(boolean
Whether the line returned should be popped off the queue of input. If this is true, this method consumes the line and further calls will return the next line of input. If false, the line returned stays in the queue and further calls to this method will return the same line again.
popLine
,
boolean
Whether all user-supplied validators should be run.
validate
)

Reads a line of input, popping or validating as desired.

public long

Returns:

The number of lines read by the reader (including skipped lines).
getLinesRead
()

This method returns the number of lines that has been read from the reader passed into the CSVReader.

public int

Returns:

The maximum number of lines allowed in a multiline record.
getMultilineLimit
()

Only useful for tests.

protected String

Returns:

The next line from the file without trailing newline, or null if there is no more input.
getNextLine
()

Reads the next line from the file.

public ICSVParser
getParser()

Returns: The CSVParser used by the reader.

public long

Returns:

The number of records (array of Strings[]) read by the reader.
getRecordsRead
()

Used for debugging purposes, this method returns the number of records that has been read from the CSVReader.

public int

Returns:

The number of lines in the CSV file to skip before processing.
getSkipLines
()

Returns the number of lines in the CSV file to skip before processing.

protected boolean

Returns:

true if the reader can no longer be read from
isClosed
()

Checks to see if the file is closed.

public Iterator<String[]>

Returns:

A String[] iterator.
iterator
()

Implements java.lang.Iterable.iterator.

Creates an Iterator for processing the CSV data.

public boolean

Returns:

True if reader will keep carriage returns, false otherwise.
keepCarriageReturns
()

Returns if the reader will keep carriage returns found in data or remove them.

public String[]

Returns:

The next line from the input, or null if there are no more lines
peek
()

Returns the next line from the input without removing it from the CSVReader and not running any validators.

private void
primeNextRecord()

Reads the next line from the buffer and converts to a string array.

public List<String[]>

Returns:

A List of String[], with each String[] representing a line of the file.
readAll
()

Reads the entire file into a List with each element being a String[] of tokens.

public String[]

Returns:

A string array with each comma-separated element as a separate entry, or null if there is no more input.
readNext
()

Reads the next line from the buffer and converts to a string array.

public String[]

Returns:

A string array with each comma-separated element as a separate entry, or null if there is no more input.
readNextSilently
()

Reads the next line from the buffer and converts to a string array without running the custom defined validators.

public void
setErrorLocale(Locale
Locale for error messages. If null, the default locale is used.
errorLocale
)

Sets the locale for all error messages.

public void
skip(int
The number of lines to skip
numberOfLinesToSkip
)

Skip a given number of lines.

private void
validateLine(long
The line number for error messages
lastSuccessfulLineRead
,
String
The input to be validated
nextLine
)

Runs all line validators on the input.

protected void
validateResult(String[]
The result of the read operation
result
,
long
Line number that the row started on
lineStartOfRow
)

Increments the number of records read if the result passed in is not null.

public boolean

Returns:

True if CSVReader will verify the reader before reads. False otherwise.
verifyReader
()

Returns if the CSVReader will verify the reader before each read.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

brback to summary
protected BufferedReader br
CONTEXT_MULTILINE_EXCEPTION_MESSAGE_SIZEback to summary
pack-priv static final int CONTEXT_MULTILINE_EXCEPTION_MESSAGE_SIZE
DEFAULT_KEEP_CRback to summary
public static final boolean DEFAULT_KEEP_CR
DEFAULT_MULTILINE_LIMITback to summary
public static final int DEFAULT_MULTILINE_LIMIT

The default limit for the number of lines in a multiline record. Less than one means no limit.

DEFAULT_SKIP_LINESback to summary
public static final int DEFAULT_SKIP_LINES

The default line to start reading.

DEFAULT_VERIFY_READERback to summary
public static final boolean DEFAULT_VERIFY_READER
errorLocaleback to summary
protected Locale errorLocale
hasNextback to summary
protected boolean hasNext
keepCRback to summary
protected boolean keepCR
lineReaderback to summary
protected LineReader lineReader
linesReadback to summary
protected long linesRead
linesSkippedback to summary
protected boolean linesSkipped
lineValidatorAggregatorback to summary
private final LineValidatorAggregator lineValidatorAggregator
MAX_WIDTHback to summary
private static final int MAX_WIDTH
multilineLimitback to summary
protected int multilineLimit
parserback to summary
protected ICSVParser parser
PASSTHROUGH_EXCEPTIONSback to summary
protected static final List<Class<? extends IOException>> PASSTHROUGH_EXCEPTIONS
peekedLineback to summary
protected String[] peekedLine
peekedLinesback to summary
protected final Queue<OrderedObject<String>> peekedLines
READ_AHEAD_LIMITback to summary
public static final int READ_AHEAD_LIMIT
recordsReadback to summary
protected long recordsRead
rowProcessorback to summary
private final RowProcessor rowProcessor
rowValidatorAggregatorback to summary
private final RowValidatorAggregator rowValidatorAggregator
skipLinesback to summary
protected int skipLines
verifyReaderback to summary
protected boolean verifyReader

Constructor Detail

CSVReaderback to summary
public CSVReader(Reader reader)

Constructs CSVReader using defaults for all parameters.

Parameters
reader:Reader

The reader to an underlying CSV source.

CSVReaderback to summary
pack-priv CSVReader(Reader reader, int line, ICSVParser icsvParser, boolean keepCR, boolean verifyReader, int multilineLimit, Locale errorLocale, LineValidatorAggregator lineValidatorAggregator, RowValidatorAggregator rowValidatorAggregator, RowProcessor rowProcessor)

Constructs CSVReader with supplied CSVParser.

This constructor sets all necessary parameters for CSVReader, and intentionally has package access so only the builder can use it.

Parameters
reader:Reader

The reader to an underlying CSV source

line:int

The number of lines to skip before reading

icsvParser:ICSVParser

The parser to use to parse input

keepCR:boolean

True to keep carriage returns in data read, false otherwise

verifyReader:boolean

True to verify reader before each read, false otherwise

multilineLimit:int

Allow the user to define the limit to the number of lines in a multiline record. Less than one means no limit.

errorLocale:Locale

Set the locale for error messages. If null, the default locale is used.

lineValidatorAggregator:LineValidatorAggregator

contains all the custom defined line validators.

rowValidatorAggregator:RowValidatorAggregator

contains all the custom defined row validators.

rowProcessor:RowProcessor

Custom row processor to run on all columns on a csv record.

Method Detail

closeback to summary
public void close() throws IOException

Implements java.io.Closeable.close.

Closes the underlying reader.

Annotations
@Override
Exceptions
IOException:
If the close fails
combineResultsFromMultipleReadsback to summary
protected String[] combineResultsFromMultipleReads(String[] buffer, String[] lastRead)

For multi-line records this method combines the current result with the result from previous read(s).

Parameters
buffer:String[]

Previous data read for this record

lastRead:String[]

Latest data read for this record.

Returns:String[]

String array with union of the buffer and lastRead arrays.

flexibleReadback to summary
private String[] flexibleRead(boolean popLine, boolean validate) throws IOException, CsvValidationException

Reads a line of input, popping or validating as desired.

Parameters
popLine:boolean

Whether the line returned should be popped off the queue of input. If this is true, this method consumes the line and further calls will return the next line of input. If false, the line returned stays in the queue and further calls to this method will return the same line again.

validate:boolean

Whether all user-supplied validators should be run.

Returns:String[]

The next line of input

Exceptions
IOException:
If this exception is thrown while reading
CsvValidationException:
If a user-supplied validator throws it
getLinesReadback to summary
public long getLinesRead()

This method returns the number of lines that has been read from the reader passed into the CSVReader.

Given the following data:

First line in the file
some other descriptive line
a,b,c

a,"b\nb",c

With a CSVReader constructed like so:
CSVReader c = builder.withCSVParser(new CSVParser())
.withSkipLines(2)
.build();

The initial call to getLinesRead() will be 0. After the first call to readNext() then getLinesRead() will return 3 (because the header was read). After the second call to read the blank line then getLinesRead() will return 4 (still a read). After the third call to readNext(), getLinesRead() will return 6 because it took two line reads to retrieve this record. Subsequent calls to readNext() (since we are out of data) will not increment the number of lines read.

Returns:long

The number of lines read by the reader (including skipped lines).

Since
3.6
getMultilineLimitback to summary
public int getMultilineLimit()

Only useful for tests.

Returns:int

The maximum number of lines allowed in a multiline record.

getNextLineback to summary
protected String getNextLine() throws IOException

Reads the next line from the file.

Returns:String

The next line from the file without trailing newline, or null if there is no more input.

Exceptions
IOException:
If bad things happen during the read
getParserback to summary
public ICSVParser getParser()
Returns:ICSVParser

The CSVParser used by the reader.

getRecordsReadback to summary
public long getRecordsRead()

Used for debugging purposes, this method returns the number of records that has been read from the CSVReader.

Given the following data:

First line in the file
some other descriptive line
a,b,c
a,"b\nb",c

With a CSVReader constructed like so:
CSVReader c = builder.withCSVParser(new CSVParser())
.withSkipLines(2)
.build();

The initial call to getRecordsRead() will be 0. After the first call to readNext() then getRecordsRead() will return 1. After the second call to read the blank line then getRecordsRead() will return 2 (a blank line is considered a record with one empty field). After third call to readNext() getRecordsRead() will return 3 because even though it reads to retrieve this record, it is still a single record read. Subsequent calls to readNext() (since we are out of data) will not increment the number of records read.

An example of this is in the linesAndRecordsRead() test in CSVReaderTest.

Returns:long

The number of records (array of Strings[]) read by the reader.

Since
3.6
See Also
Feature Request 73
getSkipLinesback to summary
public int getSkipLines()

Returns the number of lines in the CSV file to skip before processing. This is useful when there are miscellaneous data at the beginning of a file.

Returns:int

The number of lines in the CSV file to skip before processing.

isClosedback to summary
protected boolean isClosed() throws IOException

Checks to see if the file is closed.

Certain IOExceptions will be passed out, as they are indicative of a real problem, not that the file has already been closed. These exceptions are:

  • CharacterCodingException
  • CharConversionException
  • FileNotFoundException
  • UnsupportedEncodingException
  • UTFDataFormatException
  • ZipException
  • MalformedInputException

Returns:boolean

true if the reader can no longer be read from

Exceptions
IOException:
If verifyReader() was set to true certain IOExceptions will still be passed out as they are indicative of a problem, not end of file.
iteratorback to summary
public Iterator<String[]> iterator()

Implements java.lang.Iterable.iterator.

Creates an Iterator for processing the CSV data.

Returns:Iterator<String[]>

A String[] iterator.

Annotations
@Override
keepCarriageReturnsback to summary
public boolean keepCarriageReturns()

Returns if the reader will keep carriage returns found in data or remove them.

Returns:boolean

True if reader will keep carriage returns, false otherwise.

peekback to summary
public String[] peek() throws IOException

Returns the next line from the input without removing it from the CSVReader and not running any validators. Subsequent calls to this method will continue to return the same line until a call is made to readNext() or any other method that advances the cursor position in the input. The first call to readNext() after calling this method will return the same line this method does.

Returns:String[]

The next line from the input, or null if there are no more lines

Exceptions
IOException:
If bad things happen during the read operation
Since
4.2
primeNextRecordback to summary
private void primeNextRecord() throws IOException

Reads the next line from the buffer and converts to a string array. The results are stored in peekedLines and peekedLine.

Exceptions
IOException:
If bad things happen during the read
readAllback to summary
public List<String[]> readAll() throws IOException, CsvException

Reads the entire file into a List with each element being a String[] of tokens. Since the current implementation returns a java.util.LinkedList, you are strongly discouraged from using index-based access methods to get at items in the list. Instead, iterate over the list.

Returns:List<String[]>

A List of String[], with each String[] representing a line of the file.

Exceptions
IOException:
If bad things happen during the read
CsvException:
If there is a failed validator
readNextback to summary
public String[] readNext() throws IOException, CsvValidationException

Reads the next line from the buffer and converts to a string array.

Returns:String[]

A string array with each comma-separated element as a separate entry, or null if there is no more input.

Exceptions
IOException:
If bad things happen during the read
CsvValidationException:
If a user-defined validator fails
readNextSilentlyback to summary
public String[] readNextSilently() throws IOException

Reads the next line from the buffer and converts to a string array without running the custom defined validators. This is called by the bean readers when reading the header.

Returns:String[]

A string array with each comma-separated element as a separate entry, or null if there is no more input.

Exceptions
IOException:
If bad things happen during the read.
setErrorLocaleback to summary
public void setErrorLocale(Locale errorLocale)

Sets the locale for all error messages.

Parameters
errorLocale:Locale

Locale for error messages. If null, the default locale is used.

Since
4.2
skipback to summary
public void skip(int numberOfLinesToSkip) throws IOException

Skip a given number of lines.

Parameters
numberOfLinesToSkip:int

The number of lines to skip

Exceptions
IOException:
If anything bad happens when reading the file
Since
4.2
validateLineback to summary
private void validateLine(long lastSuccessfulLineRead, String nextLine) throws CsvValidationException

Runs all line validators on the input.

Parameters
lastSuccessfulLineRead:long

The line number for error messages

nextLine:String

The input to be validated

Exceptions
CsvValidationException:
Only thrown if a user-supplied validator throws it
validateResultback to summary
protected void validateResult(String[] result, long lineStartOfRow) throws CsvValidationException

Increments the number of records read if the result passed in is not null.

Parameters
result:String[]

The result of the read operation

lineStartOfRow:long

Line number that the row started on

Exceptions
CsvValidationException:
if there is a validation error caught by a custom RowValidator.
verifyReaderback to summary
public boolean verifyReader()

Returns if the CSVReader will verify the reader before each read.

By default the value is true, which is the functionality for version 3.0. If set to false the reader is always assumed ready to read - this is the functionality for version 2.4 and before.

The reason this method was needed was that certain types of readers would return false for their ready() methods until a read was done (namely readers created using Channels). This caused opencsv not to read from those readers.

Returns:boolean

True if CSVReader will verify the reader before reads. False otherwise.

Since
3.3
See Also
Bug 108