简体   繁体   English

如何在Java中以CSV格式编写ArrayList的列表

[英]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. 我想将其写入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. 方法“ writeNext”仅允许使用String []作为参数。 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 []将'ArrayList each'转换为String []时,出现运行时类型转换错误:

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

Could anyone please tell me where I am going wrong? 谁能告诉我我要去哪里错了?

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()]));
}

You can't cast Object[] into String[] because Object[] can contains Dog, Cat, Integer etc. 您无法将Object[]转换为String[]因为Object[]可以包含Dog,Cat,Integer等。

you should use overloaded List#toArray(T[]) method. 您应该使用重载的List#toArray(T [])方法。

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

Try out using the parameterized version of toArray instead - 尝试使用toArray的参数化版本-

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

edit: oops they beat me to it! 编辑:哎呀,他们击败了我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM