2010-05-10 9 views
1

Voici ma classe,SUPER CSV écriture haricots au format CSV

public class FreebasePeopleResults { 

public String intendedSearch; 
public String weight; 
public Double heightMeters; 
public Integer age; 
public String type; 
public String parents; 
public String profession; 
public String alias; 
public String children; 
public String siblings; 
public String spouse; 
public String degree; 
public String institution; 
public String wikipediaId; 
public String guid; 
public String id; 
public String gender; 
public String name; 
public String ethnicity; 
public String articleText; 
public String dob; 

public String getWeight() { 
    return weight; 
} 
public void setWeight(String weight) { 
    this.weight = weight; 
} 
public Double getHeightMeters() { 
    return heightMeters; 
} 
public void setHeightMeters(Double heightMeters) { 
    this.heightMeters = heightMeters; 
} 
public String getParents() { 
    return parents; 
} 
public void setParents(String parents) { 
    this.parents = parents; 
} 
public Integer getAge() { 
    return age; 
} 
public void setAge(Integer age) { 
    this.age = age; 
}  
public String getProfession() { 
    return profession; 
} 
public void setProfession(String profession) { 
    this.profession = profession; 
} 
public String getAlias() { 
    return alias; 
} 
public void setAlias(String alias) { 
    this.alias = alias; 
} 
public String getChildren() { 
    return children; 
} 
public void setChildren(String children) { 
    this.children = children; 
} 
public String getSpouse() { 
    return spouse; 
} 
public void setSpouse(String spouse) { 
    this.spouse = spouse; 
} 
public String getDegree() { 
    return degree; 
} 
public void setDegree(String degree) { 
    this.degree = degree; 
} 
public String getInstitution() { 
    return institution; 
} 
public void setInstitution(String institution) { 
    this.institution = institution; 
} 
public String getWikipediaId() { 
    return wikipediaId; 
} 
public void setWikipediaId(String wikipediaId) { 
    this.wikipediaId = wikipediaId; 
} 
public String getGuid() { 
    return guid; 
} 
public void setGuid(String guid) { 
    this.guid = guid; 
} 
public String getId() { 
    return id; 
} 
public void setId(String id) { 
    this.id = id; 
} 
public String getGender() { 
    return gender; 
} 
public void setGender(String gender) { 
    this.gender = gender; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public String getEthnicity() { 
    return ethnicity; 
} 
public void setEthnicity(String ethnicity) { 
    this.ethnicity = ethnicity; 
} 
public String getArticleText() { 
    return articleText; 
} 
public void setArticleText(String articleText) { 
    this.articleText = articleText; 
} 
public String getDob() { 
    return dob; 
} 
public void setDob(String dob) { 
    this.dob = dob; 
} 
public String getType() { 
    return type; 
} 
public void setType(String type) { 
    this.type = type; 
} 
public String getSiblings() { 
    return siblings; 
} 
public void setSiblings(String siblings) { 
    this.siblings = siblings; 
} 
public String getIntendedSearch() { 
    return intendedSearch; 
} 
public void setIntendedSearch(String intendedSearch) { 
    this.intendedSearch = intendedSearch; 
} 

}

Voici ma méthode écrivain CSV

import java.io.FileWriter; 
import java.io.IOException; 
import java.util.ArrayList; 

import org.supercsv.io.CsvBeanWriter; 
import org.supercsv.prefs.CsvPreference; 

public class CSVUtils { 

    public static void writeCSVFromList(ArrayList<FreebasePeopleResults> people, boolean writeHeader) throws IOException{ 

     //String[] header = new String []{"title","acronym","globalId","interfaceId","developer","description","publisher","genre","subGenre","platform","esrb","reviewScore","releaseDate","price","cheatArticleId"}; 
     FileWriter file = new FileWriter("/brian/brian/Documents/people-freebase.csv", true); 

     // write the partial data 
     CsvBeanWriter writer = new CsvBeanWriter(file, CsvPreference.EXCEL_PREFERENCE); 

     for(FreebasePeopleResults person:people){ 
      writer.write(person); 
     } 
     writer.close(); 
     // show output 
    }   
} 

Je continue de recevoir des erreurs de sortie. Voici l'erreur: Il n'y a pas de contenu à écrire pour la ligne 2 contexte: ligne: 2 Colonne: 0 ligne Raw: null

Maintenant, je sais qu'il est maintenant totalement nul, donc je suis confus.

+0

SuperCSV. Vous pouvez le trouver ici. Je suis nouveau à Java, et je suis un peu confus à savoir pourquoi cette erreur se produit. http://supercsv.sourceforge.net/ – ButtersB

Répondre

3

Il a été un certain temps, et vous avez probablement évolué depuis, mais ...

La question était en fait que vous ne fournit pas la en-tête à la méthode write(), à savoir qu'il devrait être

writer.write(person, header); 

Malheureusement, l'API est un peu trompeur dans son utilisation de la notation var-args dans le Signat La méthode write() permet de passer à null. Le javadoc indique clairement que vous ne devriez pas faire cela, mais il n'y a pas eu de vérification nulle dans l'implémentation: d'où l'exception que vous obteniez.

/** 
* Write an object 
* 
* @param source 
*   at object (bean instance) whose values to extract 
* @param nameMapping 
*   defines the fields of the class that must be written. 
*   null values are not allowed 
* @since 1.0 
*/ 
public void write(Object source, String... nameMapping) throws IOException, 
    SuperCSVReflectionException; 

Super CSV 2.0.0-beta-1 est maintenant disponible. Il conserve les var-args dans la méthode write(), mais échoue rapidement si vous fournissez une valeur nulle, de sorte que vous savez exactement ce qui ne va pas quand vous obtenez un NullPointerException avec les éléments suivants:

the nameMapping array can't be null as it's used to map from fields to columns

Il comprend également de nombreuses corrections de bugs et de nouvelles fonctionnalités (y compris le support Maven et une nouvelle extension Dozer pour la cartographie des propriétés imbriquées et des tableaux/collections).

2

Je ne vois pas où vous créez ArrayList<FreebasePeopleResults> people, mais vous pouvez vérifier qu'il a plus d'un élément. À titre d'exemple de coding to the interface, envisagez d'utiliser List<FreebasePeopleResults> people comme paramètre formel. Addenda: Avez-vous pu faire fonctionner ce Code example: Write a file with a header?

Exemple: Voici un exemple simplifié. Je pense que vous avez juste besoin de spécifier le nameMapping lorsque vous appelez write(). Ces noms déterminent les méthodes d'appel par introspection.

Sortie de la console:

 
name,age 
Alpha,1 
Beta,2 
Gamma,3 

import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.List; 
import org.supercsv.io.CsvBeanWriter; 
import org.supercsv.io.ICsvBeanWriter; 
import org.supercsv.prefs.CsvPreference; 

public class Main { 

    private static final List<Person> people = new ArrayList<Person>(); 

    public static void main(String[] args) throws IOException { 
     people.add(new Person("Alpha", 1)); 
     people.add(new Person("Beta", 2)); 
     people.add(new Person("Gamma", 3)); 
     ICsvBeanWriter writer = new CsvBeanWriter(
      new PrintWriter(System.out), CsvPreference.STANDARD_PREFERENCE); 
     try { 
      final String[] nameMapping = new String[]{"name", "age"}; 
      writer.writeHeader(nameMapping); 
      for (Person p : people) { 
       writer.write(p, nameMapping); 
      } 
     } finally { 
      writer.close(); 
     } 
    } 
} 

public class Person { 

    String name; 
    Integer age; 

    public Person(String name, Integer age) { 
     this.name = name; 
     this.age = age; 
    } 

    public Integer getAge() { 
     return age; 
    } 

    public void setAge(Integer age) { 
     this.age = age; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 
+0

Donc, vous dites utiliser le type de liste au lieu de ArrayList? – ButtersB

+0

Et je crée ArrayList personnes dans une autre méthode et le transmettre. Je sais qu'il a des données parce que si je fais un sysout (person.name) je le verrai dans ma console. – ButtersB

+0

@Butters: Oui, 'Liste ', mais c'est tangentiel à votre problème. Quel champ devrait être dans la colonne 0? – trashgod

2
CellProcessor[] processors = new CellProcessor[] { new Optional(), new NotNull(), 
       new Optional(), new Optional(), new NotNull(), new Optional()}; 

CsvBeanWriter writer = new CsvBeanWriter(file, CsvPreference.EXCEL_PREFERENCE) 

writer.write(data,properties,processors); 
Questions connexes