2013-08-13 3 views
4

나는이 예에서 수퍼 CSV website에서 dateofbirth가 선택적 열임을 보여줍니다. 두 개 이상의 선택적 열이 있으면 어떻게됩니까? 코드가 어떻게 변할 것입니까?여러 가변 열이있는 SuperCsv 사용

private static void readVariableColumnsWithCsvListReader() throws Exception { 

     final CellProcessor[] allProcessors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique) 
       new NotNull(), // firstName 
       new NotNull(), // lastName 
       new ParseDate("dd/MM/yyyy") }; // birthDate 

     final CellProcessor[] noBirthDateProcessors = new CellProcessor[] { allProcessors[0], // customerNo 
       allProcessors[1], // firstName 
       allProcessors[2] }; // lastName 

     ICsvListReader listReader = null; 
     try { 
       listReader = new CsvListReader(new FileReader(VARIABLE_CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE); 

       listReader.getHeader(true); // skip the header (can't be used with CsvListReader) 

       while((listReader.read()) != null) { 

         // use different processors depending on the number of columns 
         final CellProcessor[] processors; 
         if(listReader.length() == noBirthDateProcessors.length) { 
           processors = noBirthDateProcessors; 
         } else { 
           processors = allProcessors; 
         } 

         final List<Object> customerList = listReader.executeProcessors(processors); 
         System.out.println(String.format("lineNo=%s, rowNo=%s, columns=%s, customerList=%s", 
           listReader.getLineNumber(), listReader.getRowNumber(), customerList.size(), customerList)); 
       } 

     } 
     finally { 
       if(listReader != null) { 
         listReader.close(); 
       } 
     } 
} 

옵션 열이 끝에 있지 않고 가운데 또는 다른 곳에 있으면 어떻게 될까요?

답변

2

실제 문제는 정확한 셀 프로세서를 적용하기 위해 각 열에 어떤 데이터가 있는지 알아야한다는 것입니다. 유효한 CSV 파일 (각 행에 동일한 열 수)은 문제가되지 않지만 변수 열 CSV 파일을 다루는 경우 까다 롭습니다.

예와 같이 1 열만 선택하면 읽기 된 열의 수를 계산하고 적절한 셀 프로세서 배열을 사용해야합니다. 중요하지 않습니다. 여기서은 선택 가능한 열입니다. 왜냐하면 예측할 수 있기 때문입니다.

그러나 1 열 이상은 문제가됩니다. 예를 들어, middleNamecity는 다음 CSV 파일 선택 사항 :

firstName="Philip", middleName="Fry", lastName="New York", city=null 

또는

firstName="Philip", middleName=null, lastName="Fry", city="New York" 

그것은 더 이상 예측의 :로 읽을 수 있습니다

firstName,middleName,lastName,city 
Philip,Fry,New York 

. 열의 데이터를 검사하여 열이 무엇을 나타내야하는지 결정할 수 있습니다 (예 : 날짜가 /).하지만 그다지 강력하지는 않습니다. 그렇다고해도 몇 줄을 읽어야 할 수도 있습니다. 그것.