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?

Thus,

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

I have 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 can simply use a StringBuilder and for loop

+2
source

In this simple case, you can just append the semicolon strings. If you are using Java 8:

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

otherwise commons-lang has a join() method:

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

You mentioned Google Guava , which has a Joiner for this:

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

After digging more, I found the http://static.springsource.org/spring/docs/1.1.5/api/org/springframework/util/StringUtils.html Spring StringUtils API that can do this. Since I already use Spring, I think I will stick with this.

+3
source

Commons Apache CSV seems to be consolidating 3 other CSV libraries, although I can't find the release after 2007.

A quick search suggests OpenCSV will do what you want through 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("#"); 
+1
source

If you convert your array to Eclipse Collections (formerly GS Collections ), you can use one of the makeString() methods. If you do not pass the separator parameter, it defaults to "," (comma and space).

 MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5); String s1 = integers.makeString(","); // "1,2,3,4,5" String s2 = integers.makeString(); // "1, 2, 3, 4, 5" 

Note: I am a committer for Eclipse collections

+1
source

I created a new method for this instead of switching to 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 
0
source

All Articles