1

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 ?

Fabien Barbier
  • 1,504
  • 4
  • 28
  • 41

2 Answers2

2

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
  • 45,253
  • 22
  • 134
  • 212
0

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
  • 44,805
  • 11
  • 98
  • 117
  • If I try writer.writeAll(list), I have java.lang.ClassCastException: export.SampleJ. – Fabien Barbier Feb 17 '10 at 20:28
  • 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 Feb 17 '10 at 20:35
  • Ah, I see that finnw already posted an example code of what I said. – Petar Minchev Feb 17 '10 at 20:38
  • Thank you both ! I fix my script ! – Fabien Barbier Feb 17 '10 at 20:44
  • You could delete the answer? – hd1 Sep 06 '18 at 05:16