Java – read semicolon delimited CSV

I have the following code block, which uses opencsv to read CSV files and store column 7 The problem I face is that I use; As a separator in the CSV file, but it also acts as a separator How can I avoid this?

Unable to place '' in CSV because we got a non editable file from the client

CSVReader reader = null;
    String[] nextCsvLine = new String[50];
    String splitBy = ";";

    int count = 0;

    try {
        StringReader sr = new StringReader(new String(in,offset,len));
        reader = new CSVReader(sr);

        while ((nextCsvLine = reader.readNext()) != null) {
            for (String linewithsemicolon : nextCsvLine) {
                log.debug("Line read : "+linewithsemicolon);
                String[] b = linewithsemicolon.split(splitBy);
                if (count==0){
                    count++;
                    continue;
                }
                else    {      
                    detailItems.add(b[7]);
                    log.debug("7th position: "+b[7]);
                    count++;
                }                   
            }

Solution

Use overloaded version of opencsv with separator

CSVReader(reader,';')

Update (thanks @ Matt) – better use:

CSVReaderBuilder(reader)
    .withCSVParser(CSVParserBuilder()
    .withSeparator(';')
    .build())

I think the count is a little wrong:

try (CSVReader reader = new CSVReader(sr,';')) {
    String[] nextCsvLine;
    while ((nextCsvLine = reader.readNext()) != null) {
        int count = 0;
        for (String field: nextCsvLine) {
            log.debug("Line read : "+linewithsemicolon);
            if (count == 6) { // 7th column
                detailItems.add(field);
                log.debug("7th position: " + field);
            }                   
            count++;
        }
    }

Instead, you can do a for loop:

if (nextCsvLine.length > 6) {
             detailItems.add(nextCsvLine[6]);
         }

The seventh field should have index 6

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>