.Net ramblings
# Wednesday, 14 May 2014
Java convert array to CSV
I often use CSV for getting data in and out of mobile applications on .Net and Java.  here's a useful code snippet i use to convert an array of generic T objects into a CSV string in Java.  I use tab separated values and \n separated rows in this example.

Usage:
List<Car> cars= ... ; // whatever your array is
String CSV = GetCSV(cars);
public static String ColDelim = "\t", RowDelim = "\n";
 public static String CsvEscape(String s)
 {
     if(s == null)
         return "";
     // any tab characters in the content get stripped out. 
     // any line breaks get replaced with \r which will preserve the CSV structure and can be restored on the other side
     return s.replaceAll(ColDelim, " ").replaceAll("\r", "").replaceAll(RowDelim, "\r");
 }

 public static String CsvUnEscape(String s)
 {
     if(s == null)
         return "";
     return s.replaceAll("\r", "\r\n"); // colDelim is \n so restore any \r
                                         // characters to \r\n
 }
public static <T> String GetCSV(List<T> items)
 {    
     if(items.size() == 0)
         return "";
     StringWriter CSV = new StringWriter();
     
     // output the header row
     T first = items.get(0);
     Field[] fields = first.getClass().getDeclaredFields();
     int i=0;
     for (Field field : fields)                 
         CSV.write((i++ == 0 ? "" : ColDelim) + field.getName());
     CSV.write(RowDelim);
     
     // iterate through each item
     for(T item : items)
     {
         i=0;
         // output each row value
         for (Field field : fields)
         {
             try
             {
                 CSV.write((i == 0 ? "" : ColDelim) + Util.CsvEscape(field.get(item).toString()));
             } catch (IllegalAccessException e)
             {
                 e.printStackTrace();
             } catch (IllegalArgumentException e)
             {
                 e.printStackTrace();
             }
             i++;
         }
         CSV.write(RowDelim);            
     }        
     return CSV.toString();
 }

Wednesday, 14 May 2014 13:55:01 (GMT Daylight Time, UTC+01:00)  #    Comments [0]  Java

OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview