public class CsvParser extends Object
Since there is no CSV strict format, this parser honors as best it can the suggestions found in RFC4180, in the CSV wikipedia article and other sources.
The parser can try multiple separators, so that it can auto-detect the likely correct one. It does so by trying them one by one, checking that it finds more than one column and that all the rows have the same number of columns. If not, proceeds to the next separator.
Typical use of the parser:
CsvParserResult result = CsvParser.AUTOMATIC .withHeader(CsvParser.Header.NONE) .parse(new FileReader("table.csv"));
The parsing of each line is based on code and insights found in Mastering Regular Expressions.
Modifier and Type | Class and Description |
---|---|
static class |
CsvParser.Header
The configuration options for the header.
|
Modifier and Type | Field and Description |
---|---|
static CsvParser |
AUTOMATIC
Automatic parser: auto-detects whether the first line is a header or not
and tries the most common separators (i.e.
|
Modifier and Type | Method and Description |
---|---|
CsvParser.Header |
getHeader()
Returns the way that the parser handles the header (the first line of
the csv file).
|
String |
getSeparators()
Returns the list of separators that are going to be tried while parsing.
|
CsvParserResult |
parse(Reader reader)
Parser the text provided by the reader with the format defined in this
parser.
|
static List<Object> |
parseCSVLine(String line,
String separatorChar)
Parses a line of text representing comma separated values and returns
the values themselves.
|
CsvParser |
withHeader(CsvParser.Header header)
Creates a new parser with the given header handling.
|
CsvParser |
withSeparators(String separators)
Creates a new parser that uses the given separators.
|
public static final CsvParser AUTOMATIC
public String getSeparators()
public CsvParser withSeparators(String separators)
Each character of the string is tried until the parsing is successful.
separators
- the new list of separatorspublic CsvParser.Header getHeader()
public CsvParser withHeader(CsvParser.Header header)
header
- the header configuration for the parserpublic CsvParserResult parse(Reader reader)
If the parsing fails, this method does not throw an exception but will have information in the result. The idea is that, in the future, the parser can provide multiple reasons as why the parsing failed or event incomplete results.
reader
- a readerpublic static List<Object> parseCSVLine(String line, String separatorChar)
line
- the line to parseseparatorChar
- the regular expression for the separatorCopyright © 2015. All rights reserved.