Package toxi.data.csv

Class CSVFieldMapper

java.lang.Object
toxi.data.csv.CSVFieldMapper

public class CSVFieldMapper extends Object
This class allows the user to refer to CSV fields/columns via freely chosen IDs. This is useful in cases where the actual CSV column name is very long or the order of fields can be varying (e.g. when consuming CSV data from different sources). The class constructor expects a HashMap to establish the mapping between the custom keys and the actual CSV field names. The following example demonstrates this usage:
 HashMap<String,String> keys=new HashMap<String,String>();
 
 // creates a new alias "name" for the actual CSV field name: "What is your name?"
 keys.put("name","What is your name?");
 keys.put("phone","What is your phone number?");
 keys.put("tue","Times available on Tuesday");
 
 keys.put("id","Actual CSV field name");
 
 CSVFieldMapper mapper=new CSVFieldMapper(keys);
 ...
 
This mapper instance is then passed to a CSVParser and used to help parsing & validating the data. When a row has been successfully parsed, the CSVParser emits an event to allow clients to further process this data, e.g. by bundling it into custom data types:
 public void csvNewItemParsed(String[] fields, CSVFieldMapper map) {
   Person p = new Person();
   // use the mapper to get the field for the custom field ID "name"
   p.setName(map.get("name",fields));
   p.setPhone(map.get("phone",fields));
   ...
 }
 
  • Field Details

    • DEFAULT_DATE_FORMAT

      public static final SimpleDateFormat DEFAULT_DATE_FORMAT
  • Constructor Details

  • Method Details

    • get

      public String get(String id, String[] fields)
      Looks up the value for CSV column mapped to the given ID.
      Parameters:
      id -
      fields -
      Returns:
      value or null, if not matched.
    • getDate

      public Date getDate(String id, String[] fields)
    • getDateFormat

      public DateFormat getDateFormat()
      Returns:
      the dateFormat
    • getFloat

      public float getFloat(String id, String[] fields, float defaultValue)
    • getInt

      public int getInt(String id, String[] fields, int defaultValue)
    • getMappedFieldCount

      public int getMappedFieldCount()
    • setColumnOrder

      public boolean setColumnOrder(String[] columnTitles)
    • setDateFormat

      public void setDateFormat(DateFormat dateFormat)
      Parameters:
      dateFormat - the dateFormat to set