My code is this-
CSVReader reader = new CSVReaderBuilder(new FileReader("C://Users//himanshurai//eclipse-workspace//nike.csv")).withSeparator('|').withSkipLines(1).build();
List<TShirt> tShirtList = reader.readAll().stream().map(data -> {
//TShirt tShirt = new TShirt(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
TShirt tShirt = new TShirt();
tShirt.setId(data[0]);
tShirt.setName(data[1]);
tShirt.setColor(data[2]);
tShirt.setGender(data[3]);
tShirt.setSize(data[4]);
tShirt.setPrice(data[5]);
tShirt.setRating(data[6]);
tShirt.setIsAvailable(data[7]);
return tShirt;
}).collect(Collectors.toList());
tShirtList.forEach(System.out::println);
And this is my csv file-
My code is showing an Index out of bound error, I think it is because the csv file have '|' as a seperator instead of ',' and I tried to use withSeperator('|') method but it is showing error like the method is undefined. Is there any other way to do it?
CodePudding user response:
OK. So, in addition to the original spelling error, I think you are getting the CSVParserBuilder
and CSVReaderBuilder
classes mixed up.
According to the source code, you should be using them like this:
final CSVParser parser =
new CSVParserBuilder()
.withSeparator('\t')
.withIgnoreQuotations(true)
.build();
final CSVReader reader =
new CSVReaderBuilder(new StringReader(csv))
.withSkipLines(1)
.withCSVParser(parser)
.build();
Notice that the withSeparator
method is on CSVParserBuilder
not CSVReaderBuilder
.
(When I looked carefully ... the javadoc that I found here doesn't match the source code. It shows withSeparator
in the example, but not in the method list. Go figure.)