Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

OpenCSV what if I have '|' as a seperator instrad of ','

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-

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

OK. So, in addition to the original spelling error, I think you are getting the CSVParserBuilder and CSVReaderBuilder classes mixed up.

According to 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.

(The javadoc that I found here doesn’t match the source code. Go figure.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading