javacsvdozersupercsv

How to isolate an instance of a class with SuperCsv?


Actually I have a class ArticleModele where I store the content of the columns of the .csv, but I don't know how to access to a particular instance of the class which corresponds to a particular row in the .csv. Here is my code:

 public static ArticleModele readWithCsvDozerBeanReader() throws Exception {   
     final CellProcessor[] processors = new CellProcessor[] { 

     new Optional(),
     new Optional(),
     new Optional()

     };

     ICsvDozerBeanReader beanReader = null;
     try {
     beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME),   CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);

     beanReader.getHeader(true); // ignore the header
     beanReader.configureBeanMapping(ArticleModele.class, FIELD_MAPPING);

     ArticleModele articleModele;
     while( (articleModele = beanReader.read(ArticleModele.class, processors)) != null )        {
     System.out.println(String.format(" %s", articleModele));}
     return articleModele;
     }
     finally {
     if( beanReader != null ) {
     beanReader.close();
      }
     }
    }
  }

And here is the class:

public class ArticleModele {
    public String titre;
    public String contenu;
    public String attachement; 

    public ArticleModele(){}

    public ArticleModele(String titre, String contenu, String attachement){
    this.titre=titre;
    this.contenu=contenu;
    this.attachement=attachement;

    }
    public String getTitre(){
    return titre;
    }
    public void  setTitre(String titre){
    this.titre=titre;
    }
   public String getContenu(){
   return contenu;
  
   }
    public void setContenu(String contenu){
    this.contenu=contenu;
   }
    
    public String getAttachement(){
    return attachement;
      
      }
    public void setAttachement(String attachement){
    this.attachement=attachement;    
       }
    public String toString() {
    return String.format("ArticleModele [titre=%s, content=%s, attachement=%s]",      titre, contenu, attachement);
   }
}

Solution

  • The code returns with last result, as it overwrites articleModele.

    ArticleModele articleModele;
    while( (articleModele = beanReader.read(ArticleModele.class, processors))
            != null)             {
        System.out.println(articleModele);
    }
    return articleModele;
    

    So collect a list.

    public static List<ArticleModele> readWithCsvDozerBeanReader() throws Exception { 
        List<ArticleModele> articleModele = new ArrayList<>();
        ArticleModele articleModele;
        while( (articleModele = beanReader.read(ArticleModele.class, processors))
             != null)             {
            System.out.println(articleModele);
            articleModeles.add(articleModele);
        }
        return articleModeles;
    

    If this works you can get the ith article. And walk the articles:

    for (ArticleModele articleModele : articleModeles) { ...