读取分号分隔的csv

Sou*_*hra 3 java csv opencsv

我有下面的代码块,它使用OpenCSV读取CSV文件并存储第7列.我面临的问题是我;在CSV文件中用作分隔符,但它也,用作分隔符.我怎么能避免这个?

由于我们从客户端获取了不可编辑的文件,因此无法将""置于CSV中.

        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++;
                }                   
            }
Run Code Online (Sandbox Code Playgroud)

Joo*_*gen 8

使用带有OpenCSV分隔符的重载版本

CSVReader(reader, ';')
Run Code Online (Sandbox Code Playgroud)

更新(感谢@Matt) - 更好地使用:

CSVReaderBuilder(reader)
    .withCSVParser(CSVParserBuilder()
    .withSeparator(';')
    .build())
Run Code Online (Sandbox Code Playgroud)

我认为counting有点错误:

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++;
        }
    }
Run Code Online (Sandbox Code Playgroud)

相反,你可以做的for循环:

         if (nextCsvLine.length > 6) {
             detailItems.add(nextCsvLine[6]);
         }
Run Code Online (Sandbox Code Playgroud)

第七个字段应该有索引6.

  • 仅供参考:从最新版本开始,OpenCSV 使用构建器模式,该模式使用分隔符作为第二个参数来渲染构造函数,已弃用。现在是 `CSVReaderBuilder(reader).withCSVParser(CSVParserBuilder().withSeparator(';').build())` 请参阅 http://opencsv.sourceforge.net/apidocs/com/opencsv/CSVReader.html (5认同)
  • @Matt我冒昧地将代码移到答案中以防止废弃的代码副本。 (2认同)