2015-07-13 42 views
0

我想解析一個csv並將字段映射到一個POJO類。但是我可以看到映射沒有正確實現。使用BaneUtilBean解析CSV

我想將POJO文件頭部映射到csv。

public class CarCSVFileInputBean { 
    private long Id; 
    private String shortName; 
    private String Name; 
    private String Type; 
    private String Environment; 

    //getter and setters 
} 

可有人請看看我的代碼:

public class carCSVUtil { 
    private static Log log = LogFactory.getLog(carCSVUtil.class); 
    private static final List<String> fileHeaderFields = new ArrayList<String>(); 
    private static final String UTF8CHARSET = "UTF-8"; 
    static { 
     for (Field f : carCSVFileInputBean.class.getDeclaredFields()) { 
      fileHeaderFields.add(f.getName()); 
     }    
    } 

    public static List<carCSVFileInputBean> getCSVInputList(InputStream inputStream) { 
     CSVReader reader = null; 
     List<carCSVFileInputBean> csvList = null; 
     carCSVFileInputBean inputRecord = null; 
     String[] header = null;   
     String[] row = null; 

     try { 
      reader = new CSVReader(new InputStreamReader(inputStream, UTF8CHARSET)); 
      csvList = new ArrayList<carCSVFileInputBean>(); 
      header = reader.readNext(); 
      boolean isEmptyLine = true; 
      while ((row = reader.readNext()) != null) { 
       isEmptyLine = true; 
       if (!(row.length == 1 && StringUtils.isBlank(row[0]))) { // not an empty line, not even containing ',' 
        inputRecord = new carCSVFileInputBean(); 
        isEmptyLine = populateFields(inputRecord, header, row);  

        if (!isEmptyLine) 
         csvList.add(inputRecord); 
       } 
      }      
     } catch (IOException e) { 
      log.debug("IOException while accessing carCSVFileInputBean: " + e); 
      return null; 
     } catch (IllegalAccessException e) { 
      log.debug("IllegalAccessException while accessing carCSVFileInputBean: " + e); 
      return null; 
     } catch (InvocationTargetException e) { 
      log.debug("InvocationTargetException while copying carCSVFileInputBean properties: " + e); 
      return null; 
     } catch (Exception e) { 
      log.debug("Exception while parsing CSV file: " + e); 
      return null; 
     } finally { 
      try { 
       if (reader != null) 
        reader.close(); 
      } catch (IOException ioe) {} 
     } 

     return csvList; 
    } 

    protected static boolean populateFields(carCSVFileInputBean inputRecord, String[] header, String[] row) throws IllegalAccessException, InvocationTargetException { 
     boolean isEmptyLine = true; 
     for (int i = 0; i < row.length; i++) { 
      String val = row[i]; 

      if (!StringUtils.isBlank(val)) { 
       BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val); 
       isEmptyLine = false; 
      } 
     } 

     return isEmptyLine; 
    } 
} 
+1

您能否提供一個示例輸入和輸出以及可能出現的任何錯誤。 –

+0

'CarCSVFileInputBean'類已聲明,但'carCSVFileInputBean'用於'carCSVUtil'類。 – yanana

+0

我找到了解決方案 - csv文件中的標題預計以小寫字母開頭。 – fiddle

回答

0

我找到了解決辦法 - 在CSV文件的標題預計將開始以小寫。