问题
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";
回答1:
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
回答2:
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, ",");
回答3:
You mention Google Guava, which has the Joiner utility for this:
String s = Joiner.on(",").join(a);
回答4:
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.
回答5:
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("#");
回答6:
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
回答7:
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
来源:https://stackoverflow.com/questions/11545991/java-api-to-convert-array-to-csv