public class CSVReader extends Object implements Closeable
This reader supports records with arbitrary (variable) number of fields, multiline fields, custom separator and quote characters. It accepts CR, LF and CRLF sequence as record separators.
This reader provides its own buffering but does not perform decoding. The correct way to efficiently read CSV file with UTF-8 encoding is as follows:
CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); String[] header = reader.readRecord(); List<String[]> records = reader.readAll(); reader.close();
Constructor and Description |
---|
CSVReader(Reader reader)
Creates new CSVReader with default separator and quote characters.
|
CSVReader(Reader reader,
char separator,
char quote)
Creates new CSVReader with specified separator and quote characters.
|
Modifier and Type | Method and Description |
---|---|
void |
close()
Closes the stream.
|
int |
getLineNumber()
Returns current line number.
|
int |
getRecordNumber()
Returns current record number.
|
List<String[]> |
readAll()
Reads and returns all records or empty list if stream has ended.
|
String |
readField()
Reads and returns a single field of the current record or null if record has ended.
|
String[] |
readRecord()
Reads and returns a remaining fields of the current record or null if stream has ended.
|
public CSVReader(Reader reader)
NullPointerException
- if reader is nullpublic CSVReader(Reader reader, char separator, char quote)
NullPointerException
- if reader is nullIllegalArgumentException
- if separator or quote characters are invalidpublic int getLineNumber()
public int getRecordNumber()
public String readField() throws IOException
CSVFormatException
- if input stream does not conform to the CSV formatIOException
- If an I/O error occurspublic String[] readRecord() throws IOException
readField()
method.
Returns array of length 1 with single empty string if record is empty (empty line).
Returns empty strings for those fields that are empty.
This method advances to the next record upon completion.CSVFormatException
- if input stream does not conform to the CSV formatIOException
- If an I/O error occurspublic List<String[]> readAll() throws IOException
CSVFormatException
- if input stream does not conform to the CSV formatIOException
- If an I/O error occurspublic void close() throws IOException
close
in interface Closeable
close
in interface AutoCloseable
IOException
- If an I/O error occursCopyright © 2015 Devexperts. All Rights Reserved.