Anand Hemmige
Anand Hemmige

Reputation: 3683

Java API to convert Array to CSV

Suppose I have an array of int, float, string etc. Is there any utility API (e.g. Commons, Guava) that will give me a comma separated string?

Like so,

int[] a = {1,2,3,4,5}. 
String s = magicAPI.getCSV(a); // s == "1,2,3,4,5";

Upvotes: 15

Views: 28787

Answers (6)

Yogamurthy
Yogamurthy

Reputation: 998

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

Upvotes: 0

assylias
assylias

Reputation: 328598

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, ",");

Upvotes: 33

munyengm
munyengm

Reputation: 15479

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

Upvotes: 4

Anand Hemmige
Anand Hemmige

Reputation: 3683

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.

Upvotes: 3

millimoose
millimoose

Reputation: 39950

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

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

Upvotes: 6

Brian Agnew
Brian Agnew

Reputation: 272247

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("#");

Upvotes: 1

Related Questions