Added a convenient format() method in CSVFormat replacing CSVUtils.printLine()

git-svn-id: https://svn.apache.org/repos/asf/commons/sandbox/csv/trunk@1297091 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Emmanuel Bourg 2012-03-05 15:42:03 +00:00
parent a53c76b43a
commit 1a35541867
3 changed files with 26 additions and 36 deletions

View File

@ -17,8 +17,10 @@
package org.apache.commons.csv;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringWriter;
/**
* The format specification of a CSV file.
@ -215,6 +217,22 @@ public class CSVFormat implements Cloneable, Serializable {
return new CSVParser(in, this);
}
/**
* Format the specified values.
*
* @param values the values to format
*/
public String format(String... values) {
StringWriter out = new StringWriter();
try {
new CSVPrinter(out, this).println(values);
} catch (IOException e) {
// should not happen
}
return out.toString().trim();
}
protected CSVFormat clone() {
try {
return (CSVFormat) super.clone();

View File

@ -18,7 +18,6 @@ package org.apache.commons.csv;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
/**
* Utility methods for dealing with CSV files
@ -38,41 +37,6 @@ public class CSVUtils {
public CSVUtils() {
}
/**
* Converts an array of string values into a single CSV line. All
* <code>null</code> values are converted to the string <code>"null"</code>,
* all strings equal to <code>"null"</code> will additionally get quotes
* around.
*
* @param values the value array
* @return the CSV string, will be an empty string if the length of the
* value array is 0
*/
public static String printLine(CSVFormat format, String... values) {
// set up a CSVUtils
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, format);
// check for null values an "null" as strings and convert them
// into the strings "null" and "\"null\""
for (int i = 0; i < values.length; i++) {
if (values[i] == null) {
values[i] = "null";
} else if (values[i].equals("null")) {
values[i] = "\"null\"";
}
}
// convert to CSV
try {
csvPrinter.println(values);
} catch (IOException e) {
// should not happen with StringWriter
}
// as the resulting string has \r\n at the end, we will trim that away
return stringWriter.toString().trim();
}
// ======================================================
// static parsers
// ======================================================

View File

@ -60,4 +60,12 @@ public class CSVFormatTest extends TestCase {
assertEquals(false, format.withEmptyLinesIgnored(false).isEmptyLinesIgnored());
assertEquals(false, format.withUnicodeEscapesInterpreted(false).isUnicodeEscapesInterpreted());
}
public void testFormat() {
CSVFormat format = CSVFormat.DEFAULT;
assertEquals("", format.format());
assertEquals("a,b,c", format.format("a", "b", "c"));
assertEquals("\"x,y\",z", format.format("x,y", "z"));
}
}