views:

597

answers:

2

I need to parse 2 dimensional list, here is my schema list :

list (size=12) 
->[0] = "export.SampleJ:12432"  
   --> id = 12432  
   --> dateCreatedSample = "Tue Feb 03 19:04:23 CST 2009"  
   --> ttId = 0  
   --> chipId = 1012  
   --> ...  
->[1] = "export.SampleJ:12433"
   --> id = 12433
   --> ...
->[2] ...

I tried :

 List<String[]> allElements = list.readAll();
 StringWriter sw = new StringWriter();
 CSVWriter writer = new CSVWriter(sw);
 writer.writeAll(allElements);

but I have this error : No signature of method: java.util.ArrayList.readAll() is applicable for argument types: () values: []

Also tried :

 CSVWriter writer = new CSVWriter(new FileWriter("MyFile.csv"));
 String[] entries = list;
 writer.writeNext(entries);
 writer.close();

I get a csv file, but with only : "export.SampleJ:12432", "export.SampleJ:12432", ...

How can I parse id, dateCreatedSample, etc ?

Is there a way to connect my list directly with opencsv ?

A: 

You can use the writer.writeAll(list) and reader.readAll() methods. I don't see a point why it should not work.

Edit: Ignore this post. I was too sleepy to see the two dimensions.

Petar Minchev
If I try writer.writeAll(list), I have java.lang.ClassCastException: export.SampleJ.
Fabien Barbier
I get it now. Just iterate through your list and for every object in it, build a String[] array manually. Then call writeNext(string array). The problem was that OpenCSV can't magically write objects. You must either have a list of String[] and then call writeAll(list) or build row by row a String[] as I mentioned above and write every row with writeNext(String[]);
Petar Minchev
Ah, I see that finnw already posted an example code of what I said.
Petar Minchev
Thank you both ! I fix my script !
Fabien Barbier
+2  A: 

You need to add a method to SampleJ to convert it into a String[], e.g.

class SampleJ {
    // ...
    public String[] toStringArray =
        Arrays.asList(String.valueOf(getId()),
                      String.valueOf(getDateCreatedSample()),
                      String.valueOf(getTtId()),
                      String.valueOf(getChipId()));
}

then loop to write all lines, e.g.

for (SampleJ elem: list) {
    writer.writeNext(elem.toStringArray());
}
finnw
Good example, I fix my class, problem solved ! Thanks
Fabien Barbier