2017-10-20 147 views
2

我有下面的代码块,它使用OpenCSV读取CSV文件并存储第7列。我面对的问题是我使用;作为CSV文件的分隔符,但它也需要,作为分隔符。我怎样才能避免这种情况?阅读分号csv

将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++; 
       }     
      } 
+0

这是哪种语言?它看起来像Java。您需要用编程语言标记您的问题 - 请参阅您的问题下的“编辑”链接。 –

+0

是的,它的JAVA遗憾忘记链接。 –

+1

您发布的代码对逗号没有反应。请提供[mcve]。 – Thomas

回答

4

使用重载版本的OpenCSV

CSVReader(reader, ';') 

分离我觉得count ING做有点不对劲:

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++; 
     } 
    } 

而是for循环你可以已完成:

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

其中第七个字段应该具有索引6。

+0

你的意思是像读者=新的CSVReader(sr,';'); 这会在分号的第一个实例后中断,之后不会读取。 –

+0

请参见zetcode.com上的[ReadNumbers2.java](http://zetcode.com/articles/opencsv/)。我会为答案添加一些代码。 –

+0

谢谢,这完全符合我的需要。 –