Результат CSV печатается более одного раза

#java #restlet

#java #restlet

Вопрос:

Я использую csvwriter для получения выходных данных в формате csv на Java.

У меня есть процедура, которая возвращает данные в следующем формате:

   result  didNumber     businessName  actualNumber    
          91930921800  TEMP NAME  
          917930921800 TEMP NAME  
 NOANSWER 917930921800 TEMP NAME  9845618737
 NOANSWER 917930921800 TEMP NAME  9845618737
 NOANSWER 917930921800 TEMP NAME  8951577970
 NOANSWER 917930921801 TEMP NAME  9920036823
 NOANSWER 917930921802 TEMP NAME  8762224646
 NOANSWER 917930921802 TEMP NAME  9845618737
 NOANSWER 917930921803 TEMP NAME  9448017755
 NOANSWER 917930921803 TEMP NAME  9845618737
 NOANSWER 917930921895 TEMP NAME  9448017755
DIALING 917930921800 TEMP NAME  8951577970
DIALING 917930921802 TEMP NAME  8762224646
  

Вот мой Java-код для записи в csv-файл.

  public void writeCSVData(ResultSet cdrs,String fileName) throws IOException, SQLException {
  String methodName = "writeCSVData";
  logger.debug("entering in "   methodName   " in "   className);
  BufferedWriter writer = new BufferedWriter(new FileWriter(createFile(fileName).getAbsoluteFile()));
  CSVWriter csvWriter = new CSVWriter(writer);
  String currentDid = null;
  String prevDid = null;
  String businessName = null;
  String businessReference = null;
  String actualNumber = null;
     StringBuilder result = new StringBuilder();
     String[] entries = null;
     int count = 0;
  while (cdrs.next()) {              
   currentDid = cdrs.getString("didNumber");
   if (count == 0){
    prevDid = currentDid;
    result.append(currentDid);
    result.append(",");
    businessName = cdrs.getString("businessName");
    result.append(businessName);
       result.append(",");
    businessReference = cdrs.getString("businessReference");
    result.append(businessReference);
       result.append(",");
       actualNumber = cdrs.getString("actualNumber");
    result.append(actualNumber);
    count  ;
    continue;
   }
     if(!prevDid.equals(currentDid)){
    entries = result.toString().split(",");
       result.append("n");
    csvWriter.writeNext(entries);
    prevDid = currentDid;
    currentDid = cdrs.getString("didNumber");
    result.append(currentDid);
       result.append(",");
    businessName = cdrs.getString("businessName");
    result.append(businessName);
       result.append(",");
    businessReference = cdrs.getString("businessReference");
    result.append(businessReference);
       result.append(",");
    actualNumber = cdrs.getString("actualNumber");
    result.append(actualNumber);
       result.append(",");
    continue;
   }
      if(prevDid.equals(currentDid)){
    prevDid = currentDid;
    result.append(",");
    actualNumber = cdrs.getString("actualNumber");
    result.append(actualNumber);
       result.append(",");
    continue; 
      }


  }
 }
  

По сути, я записываю все фактическое число для didNumber в одной строке и записываю его в csv.

Ответ правильный, только дело в том, что каждая строка повторяется более одного раза.

Вот мой вывод:

 "917930921800","TEMP NAME","null","null","null","","9845618737","","8951577970","","9845618737","","8951577970"
"917930921800","TEMP NAME","null","null","null","","9845618737","","8951577970","","9845618737","","8951577970","
917930921801","TEMP NAME","null","9920036823"
"917930921800","TEMP NAME","null","null","null","","9845618737","","8951577970","","9845618737","","8951577970","
917930921801","TEMP NAME","null","9920036823","
917930921802","TEMP NAME","null","8762224646","","8762224646","","9845618737"
"917930921800","TEMP NAME","null","null","null","","9845618737","","8951577970","","9845618737","","8951577970","
917930921801","TEMP NAME","null","9920036823","
917930921802","TEMP NAME","null","8762224646","","8762224646","","9845618737","
917930921803","TEMP NAME","null","9448017755","","9845618737
  

В идеале ответ должен быть таким:

  "917930921800","TEMP NAME","null","null","null","","9845618737","","8951577970","","9845618737","","8951577970"
    917930921801","TEMP NAME","null","9920036823","
    917930921802","TEMP NAME","null","8762224646","","8762224646","","9845618737"
    917930921803","TEMP NAME","null","9448017755","","9845618737
  

Пожалуйста, покажите мне, что я мог сделать неправильно.

Комментарии:

1. Если вам нужна помощь, попробуйте изолировать проблему и сделать код более чистым. По крайней мере, удалите инструкции по отладке, они нам совсем не помогают..

2. Используйте библиотеку CSV, такую как opencsv.sourceforge.net .

Ответ №1:

Я бы порекомендовал вам использовать какую-нибудь библиотеку, подобную opecsv, как предложил Лутц.

Возможная проблема здесь .

 StringBuilder result = new StringBuilder();
  

Вы удаляете эту строку вне цикла и не сбрасываете ее после записи строки.

Добавьте следующую строку ниже csvWriter.writeNext(entries);

 result.delete(0, result.length());
  

Это приведет к сбросу строки.