如何在 Java 中将 ArrayList 列表写入 CSV 格式 [英] How to write a List of ArrayLists to CSV format in Java

查看:74
本文介绍了如何在 Java 中将 ArrayList 列表写入 CSV 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的数据:

   List<ArrayList<String>>

我想将其写入 CSV.下面是我的代码:

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

'writeNext' 方法只允许 String[] 作为它的参数.当我尝试使用 Object[ ] 将 cast 'ArrayList each' 输入 String[] 时,如下所示,出现运行时类型转换错误:

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?

推荐答案

你不能将 Object[] 转换成 String[] 因为 Object[] 可以包含 Dog、Cat、Integer 等.

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

你应该使用重载的 List#toArray(T[]) 方法.

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

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

这篇关于如何在 Java 中将 ArrayList 列表写入 CSV 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆