You can use one of the predefined formats:
For example:
CSVParser parser = CSVFormat.EXCEL.parse(reader);
The {@link CSVParser} provides static methods to parse other input types, for example:
CSVParser parser = CSVParser.parse(file, StandardCharsets.US_ASCII, CSVFormat.EXCEL);
You can extend a format by calling the {@code with} methods. For example:
CSVFormat.EXCEL .withNullString("N/A") .withIgnoreSurroundingSpaces(true);
To define the column names you want to use to access records, write:
CSVFormat.EXCEL.withHeader("Col1", "Col2", "Col3");
Calling {@link #withHeader(String)} let's you use the given names to address values in a {@link CSVRecord}, and assumes that your CSV source does not contain a first record that also defines column names. If it does, then you are overriding this metadata with your names and you should skip the first record by calling {@link #withSkipHeaderRecord(boolean)} with {@code true}.
You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write:
Reader in = ...; CSVFormat.EXCEL.withHeader("Col1", "Col2", "Col3").parse(in);
For other input types, like resources, files, and URLs, use the static methods on {@link CSVParser}.
If your source contains a header record, you can simplify your code and safely reference columns, by using {@link #withHeader(String)} with no arguments:
CSVFormat.EXCEL.withHeader();
This causes the parser to read the first record and use its values as column names. Then, call one of the {@link CSVRecord} get method that takes a String column name argument:
String value = record.get("Col1");
This makes your code impervious to changes in column order in the CSV file.
This class is immutable.
@version $Id: CSVFormat.java 1617076 2014-08-10 09:23:01Z britter $
|
|
|
|
|
|