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

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

问题描述

我有以下格式的数据:

  List< ArrayList< String> 

我想将它写入CSV。下面是我的代码:

  private void 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自动生成的catch块
e.printStackTrace();
}

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


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

方法writeNext只允许String []它的参数。当我试图使用一个Object []类型转换'ArrayList each'到String []如下所示,我得到运行时类型转换错误:

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

有人可以告诉我我在哪里出错吗?

Object [] 转换为 String [] 因为 Object [] 可以包含Dog,Cat,Integer等。



href =http://docs.oracle.com/javase/7/docs/api/java/util/List.html#toArray%28T[]%29 =nofollow> list#toArray(T [] )方法。

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


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?

解决方案

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

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

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