Reputation: 369
I hope the kind people here can help me with my CSV situation. I only need to read the first 3 columns in the CSV that i'm using. I have no control in the number of columns that the CSV file has and there are no headers available. I tried using the partial read with CSVBeanReader (https://super-csv.github.io/super-csv/examples_partial_reading.html) but I keep getting the "nameMapping array and the number of columns read" error. I would like to ask if the partial reading example works for the supercsv version 2.4.0 which i'm currently using. See below the code I used which I patterned similar to the partial read example
public class MainPartialRead {
public void partialRead() throws Exception {
ICsvBeanReader beanReader = null;
String csv_filename = "test2.csv";
try {
beanReader = new CsvBeanReader(new FileReader(csv_filename), CsvPreference.STANDARD_PREFERENCE);
beanReader.getHeader(true); // skip past the header (we're defining our own)
System.out.println("beanreader Length: " + beanReader.length());
// only map the first 3 columns - setting header elements to null means those columns are ignored
final String[] header = new String[]{"column1", "column2", "column3", null, null, null, null, null,
null, null};
// no processing required for ignored columns
final CellProcessor[] processors = new CellProcessor[]{new NotNull(), new NotNull(),
new NotNull(), null, null, null, null, null, null, null};
beanCSVReport customer;
while ((customer = beanReader.read(beanCSVReport.class, header, processors)) != null) {
System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(),
beanReader.getRowNumber(), customer));
}
} finally {
if (beanReader != null) {
beanReader.close();
}
}
}
Here is the sample CSV file i'm using:
466,24127,abc,53516
868,46363,hth,249
Upvotes: 0
Views: 1291
Reputation: 1611
you did not mention the complete error message.
Exception in thread "main" java.lang.IllegalArgumentException: the nameMapping array and the number of columns read should be the same size
(nameMapping length = 10, columns = 4)
From this it is very clear what the issue is. You have just 4 columns in the csv file but you have mentioned mapping for 10 columns, 7 of them null.
Removing 6 nulls from header and processors fixes the issue.
another point to note. The following code skips the first line assuming it to be header as you instructed but in fact it is not a header row. You should not call this method.
beanReader.getHeader(true);
Upvotes: 1