Srikanth Kandalam
Srikanth Kandalam

Reputation: 1045

How to write a List of ArrayLists to CSV format in Java

I have data in the below format:

   List<ArrayList<String>>

I want to write it to CSV. Below is my code:

private static void writeToCSV(List<ArrayList<String>> csvInput) throws IOException{

String csv = "C:\\output.csv";
CSVWriter writer = null;

try {
    writer = new CSVWriter(new FileWriter(csv));
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

for(ArrayList<String> each: csvInput){
    writer.writeNext(each);
}


writer.close();
}//end of writeTOCSV

The method 'writeNext' allows only String[ ] as it's argument. When I try to type cast 'ArrayList each' into String[] using an Object[ ] as shown below, I am getting run time type casting error:

   Object[] eachTemp = each.toArray();
   writer.writeNext((String[]) eachTemp);

Could anyone please tell me where I am going wrong?

Upvotes: 0

Views: 11240

Answers (3)

radar
radar

Reputation: 605

Try out using the parameterized version of toArray instead -

    String[] eachTemp = each.toArray(new String[each.size()]);
    writer.writeNext(eachTemp);

edit: oops they beat me to it!

Upvotes: 2

Braj
Braj

Reputation: 46841

You can't cast Object[] into String[] because Object[] can contains Dog, Cat, Integer etc.

you should use overloaded List#toArray(T[]) method.

List<String> list = new ArrayList<String>();
String[] array = list.toArray(new String[] {});

Upvotes: 3

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

You are converting your list to array of objects. To create array of strings do:

for(ArrayList<String> each: csvInput){
    writer.writeNext(each.toArray(new String[each.size()]));
}

Upvotes: 2

Related Questions