Java API to convert Array to CSV

╄→гoц情女王★ 提交于 2019-11-30 18:18:29

I've used OpenCSV in the past.

StringWriter stringWriter = new StringWriter();
int[] a = {1,2,3,4,5};
String[] b = new String[a.length];
for ( int i = 0; i < a.length; i++) {
    b[i] = a[i];
}
CSVWriter csvWriter = new CSVWriter(stringWriter, ",");
csvWriter.writeNext(b);

However, for such a trivial example you might want to just use the a StringBuilder and a for loop

For this simple use case, you can simply join the strings with comma. If you use Java 8:

String csv = String.join(",", yourArray);

otherwise commons-lang has a join() method:

String csv = org.apache.commons.lang3.StringUtils.join(yourArray, ",");

You mention Google Guava, which has the Joiner utility for this:

String s = Joiner.on(",").join(a);

After digging more, I found http://static.springsource.org/spring/docs/1.1.5/api/org/springframework/util/StringUtils.html StringUtils API in Spring that can do it. Since , I'm already using Spring, I guess I will stick with it.

Commons Apache CSV appears to consolidate 3 other CSV libraries, although I can't find a release post-2007.

A quick look suggests OpenCSV will do what you want via a CSVWriter.

 CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
 // feed in your array (or convert your data to an array)
 String[] entries = "first#second#third".split("#");

I have created a new method to do thisinstead of going for openCSV

public String convertArrayToCsv(String[] IncomingArray)
{
    StringBuilder sb=new StringBuilder();
    for (int i=0;i<IncomingArray.length;i++)
    {
        sb=sb.append(IncomingArray[i]);
        if(i != IncomingArray.length-1)
        {
            sb.append(",");
        }
    }
    return sb.toString();
}//end of convertArrayToCsv method

If you convert your array into an Eclipse Collections primitive container, you can use one of the makeString() methods. If you don't pass in separator parameter, it defaults to ", " (comma and space).

int[] array = {1,2,3,4,5};
IntList intList = IntLists.mutable.with(array);
String s1 = intList.makeString(",");
System.out.println(s1); // "1,2,3,4,5"
String s2 = intList.makeString();
System.out.println(s2); // "1, 2, 3, 4, 5"

Note: I am a committer for Eclipse Collections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!