Skip to content

Commit f6f9fc1

Browse files
committed
Pulled some static methods into a CSVUtils class, switched CSVPrinter to use a CSVStrategy though it doesn't use it fully yet, added a COMMENTS_DISABLED constant instead of relying on (char) 0.
git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/sandbox/csv/trunk@415323 13f79535-47bb-0310-9956-ffa450edef68
1 parent 10743e1 commit f6f9fc1

7 files changed

Lines changed: 305 additions & 269 deletions

File tree

src/java/org/apache/commons/csv/CSVParser.java

Lines changed: 2 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -90,53 +90,6 @@ class Token {
9090
}
9191
}
9292

93-
// ======================================================
94-
// static parsers
95-
// ======================================================
96-
97-
/**
98-
* Parses the given String according to the default CSV strategy.
99-
*
100-
* @param s CSV String to be parsed.
101-
* @return parsed String matrix (which is never null)
102-
* @throws IOException in case of error
103-
* @see #setStrategy()
104-
*/
105-
public static String[][] parse(String s) throws IOException {
106-
if (s == null) {
107-
throw new IllegalArgumentException("Null argument not allowed.");
108-
}
109-
String[][] result = (new CSVParser(new StringReader(s))).getAllValues();
110-
if (result == null) {
111-
// since CSVStrategy ignores empty lines an empty array is returned
112-
// (i.e. not "result = new String[][] {{""}};")
113-
result = new String[0][0];
114-
}
115-
return result;
116-
}
117-
118-
/**
119-
* Parses the first line only according to the default CSV strategy.
120-
*
121-
* Parsing empty string will be handled as valid records containing zero
122-
* elements, so the following property holds: parseLine("").length == 0.
123-
*
124-
* @param s CSV String to be parsed.
125-
* @return parsed String vector (which is never null)
126-
* @throws IOException in case of error
127-
* @see #setStrategy()
128-
*/
129-
public static String[] parseLine(String s) throws IOException {
130-
if (s == null) {
131-
throw new IllegalArgumentException("Null argument not allowed.");
132-
}
133-
// uh,jh: make sure that parseLine("").length == 0
134-
if (s.length() == 0) {
135-
return new String[0];
136-
}
137-
return (new CSVParser(new StringReader(s))).getLine();
138-
}
139-
14093
// ======================================================
14194
// the constructor
14295
// ======================================================
@@ -366,7 +319,7 @@ protected Token nextToken() throws IOException {
366319
eol = isEndOfLine(c);
367320
}
368321
// ok, start of token reached: comment, encapsulated, or token
369-
if (c == strategy.getCommentStart()) {
322+
if (!strategy.isCommentingDisabled() && c == strategy.getCommentStart()) {
370323
// ignore everything till end of line and continue (incr linecount)
371324
in.readLine();
372325
tkn = nextToken();
@@ -602,7 +555,7 @@ public CSVStrategy getStrategy() {
602555
// ======================================================
603556

604557
/**
605-
* @return true if the given char is a whitespache character
558+
* @return true if the given char is a whitespace character
606559
*/
607560
private boolean isWhitespace(int c) {
608561
return Character.isWhitespace((char) c);

src/java/org/apache/commons/csv/CSVPrinter.java

Lines changed: 25 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,7 @@ public class CSVPrinter {
3131
/** True if we just began a new line. */
3232
protected boolean newLine = true;
3333

34-
/** Character used to start comments. (Default is '#') */
35-
protected char commentStart = '#';
36-
37-
/** Character used to separate entities. (Default is ',') */
38-
protected char separatorChar = ',';
34+
private CSVStrategy strategy = CSVStrategy.DEFAULT_STRATEGY;
3935

4036
/**
4137
* Create a printer that will print values to the given
@@ -66,67 +62,33 @@ public CSVPrinter(Writer out) {
6662
}
6763

6864

69-
/**
70-
* Create a printer that will print values to the given
71-
* stream. Character to byte conversion is done using
72-
* the default character encoding.
73-
*
74-
* @param out stream to which to print.
75-
* @param commentStart Character used to start comments.
76-
*/
77-
public CSVPrinter(OutputStream out, char commentStart) {
78-
this(out);
79-
this.commentStart = commentStart;
80-
}
81-
82-
83-
/**
84-
* Create a printer that will print values to the given
85-
* stream.
86-
*
87-
* @param out stream to which to print.
88-
* @param commentStart Character used to start comments.
89-
*/
90-
public CSVPrinter(Writer out, char commentStart) {
91-
this(out);
92-
this.commentStart = commentStart;
93-
}
94-
95-
/**
96-
* Gets the comment start character.
97-
*
98-
* @return the commentStart character
99-
*/
100-
public char getCommentStart() {
101-
return commentStart;
102-
}
65+
// ======================================================
66+
// strategies
67+
// ======================================================
10368

10469
/**
105-
* Sets the comment start character.
106-
*
107-
* @param commentStart commentStart character to set.
70+
* Sets the specified CSV Strategy
71+
*
72+
* @return current instance of CSVParser to allow chained method calls
10873
*/
109-
public void setCommentStart(char commentStart) {
110-
this.commentStart = commentStart;
74+
public CSVPrinter setStrategy(CSVStrategy strategy) {
75+
this.strategy = strategy;
76+
return this;
11177
}
11278

11379
/**
114-
* Gets the separator character.
115-
*
116-
* @return Returns the separatorChar.
117-
*/
118-
public char getSeparatorChar() {
119-
return separatorChar;
120-
}
121-
/**
122-
* Sets the separator character.
80+
* Obtain the specified CSV Strategy
12381
*
124-
* @param separatorChar The separatorChar to set.
82+
* @return strategy currently being used
12583
*/
126-
public void setSeparatorChar(char separatorChar) {
127-
this.separatorChar = separatorChar;
84+
public CSVStrategy getStrategy() {
85+
return this.strategy;
12886
}
12987

88+
// ======================================================
89+
// printing implementation
90+
// ======================================================
91+
13092
/**
13193
* Print the string as the last value on the line. The value
13294
* will be quoted if needed.
@@ -197,10 +159,13 @@ public void println(String[][] values) {
197159
* @param comment the comment to output
198160
*/
199161
public void printlnComment(String comment) {
162+
if(this.strategy.isCommentingDisabled()) {
163+
return;
164+
}
200165
if (!newLine) {
201166
out.println();
202167
}
203-
out.print(commentStart);
168+
out.print(this.strategy.getCommentStart());
204169
out.print(' ');
205170
for (int i = 0; i < comment.length(); i++) {
206171
char c = comment.charAt(i);
@@ -212,7 +177,7 @@ public void printlnComment(String comment) {
212177
// break intentionally excluded.
213178
case '\n' :
214179
out.println();
215-
out.print(commentStart);
180+
out.print(this.strategy.getCommentStart());
216181
out.print(' ');
217182
break;
218183
default :
@@ -248,7 +213,7 @@ public void print(String value) {
248213
}
249214
for (int i = 0; i < value.length(); i++) {
250215
c = value.charAt(i);
251-
if (c == '"' || c == separatorChar || c == '\n' || c == '\r') {
216+
if (c == '"' || c == this.strategy.getDelimiter() || c == '\n' || c == '\r') {
252217
quote = true;
253218
}
254219
}
@@ -265,7 +230,7 @@ public void print(String value) {
265230
if (newLine) {
266231
newLine = false;
267232
} else {
268-
out.print(separatorChar);
233+
out.print(this.strategy.getDelimiter());
269234
}
270235
if (quote) {
271236
out.print(escapeAndQuote(value));
@@ -276,40 +241,6 @@ public void print(String value) {
276241
}
277242

278243

279-
/**
280-
* Converts an array of string values into a single CSV line. All
281-
* <code>null</code> values are converted to the string <code>"null"</code>,
282-
* all strings equal to <code>"null"</code> will additionally get quotes
283-
* around.
284-
*
285-
* @param values the value array
286-
* @return the CSV string, will be an empty string if the length of the
287-
* value array is 0
288-
*/
289-
public static String printLine(String[] values) {
290-
291-
// set up a CSVPrinter
292-
StringWriter csvWriter = new StringWriter();
293-
CSVPrinter csvPrinter = new CSVPrinter(csvWriter);
294-
295-
// check for null values an "null" as strings and convert them
296-
// into the strings "null" and "\"null\""
297-
for (int i = 0; i < values.length; i++) {
298-
if (values[i] == null) {
299-
values[i] = "null";
300-
} else if (values[i].equals("null")) {
301-
values[i] = "\"null\"";
302-
}
303-
}
304-
305-
// convert to CSV
306-
csvPrinter.println(values);
307-
308-
// as the resulting string has \r\n at the end, we will trim that away
309-
return csvWriter.toString().trim();
310-
}
311-
312-
313244
/**
314245
* Enclose the value in quotes and escape the quote
315246
* and comma characters that are inside.

src/java/org/apache/commons/csv/CSVStrategy.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,11 @@ public class CSVStrategy {
2929
private boolean interpretUnicodeEscapes;
3030
private boolean ignoreEmptyLines;
3131

32-
public static CSVStrategy DEFAULT_STRATEGY = new CSVStrategy(',', '"', (char) 0, true, false, true);
33-
public static CSVStrategy EXCEL_STRATEGY = new CSVStrategy(';', '"', (char) 0, false, false, false);
32+
public static char COMMENTS_DISABLED = (char) 0;
33+
34+
public static CSVStrategy DEFAULT_STRATEGY = new CSVStrategy(',', '"', COMMENTS_DISABLED, true, false, true);
35+
public static CSVStrategy EXCEL_STRATEGY = new CSVStrategy(';', '"', COMMENTS_DISABLED, false, false, false);
36+
public static CSVStrategy TDF_STRATEGY = new CSVStrategy(' ', '"', COMMENTS_DISABLED, true, false, true);
3437

3538

3639
public CSVStrategy(char delimiter, char encapsulator, char commentStart) {
@@ -74,6 +77,7 @@ public CSVStrategy(
7477

7578
public void setCommentStart(char commentStart) { this.commentStart = commentStart; }
7679
public char getCommentStart() { return this.commentStart; }
80+
public boolean isCommentingDisabled() { return this.commentStart == COMMENTS_DISABLED; }
7781

7882
public void setIgnoreLeadingWhitespaces(boolean ignoreLeadingWhitespaces) { this.ignoreLeadingWhitespaces = ignoreLeadingWhitespaces; }
7983
public boolean getIgnoreLeadingWhitespaces() { return this.ignoreLeadingWhitespaces; }
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/*
2+
* Copyright 2005 The Apache Software Foundation.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.apache.commons.csv;
17+
18+
import java.io.StringWriter;
19+
import java.io.StringReader;
20+
import java.io.IOException;
21+
22+
/**
23+
* Utility methods for dealing with CSV files
24+
*/
25+
public class CSVUtils {
26+
27+
/**
28+
* <p><code>CSVUtils</code> instances should NOT be constructed in
29+
* standard programming.
30+
*
31+
* <p>This constructor is public to permit tools that require a JavaBean
32+
* instance to operate.</p>
33+
*/
34+
public CSVUtils() {
35+
}
36+
37+
/**
38+
* Converts an array of string values into a single CSV line. All
39+
* <code>null</code> values are converted to the string <code>"null"</code>,
40+
* all strings equal to <code>"null"</code> will additionally get quotes
41+
* around.
42+
*
43+
* @param values the value array
44+
* @return the CSV string, will be an empty string if the length of the
45+
* value array is 0
46+
*/
47+
public static String printLine(String[] values) {
48+
// set up a CSVUtils
49+
StringWriter stringWriter = new StringWriter();
50+
CSVPrinter csvPrinter = new CSVPrinter(stringWriter);
51+
52+
// check for null values an "null" as strings and convert them
53+
// into the strings "null" and "\"null\""
54+
for (int i = 0; i < values.length; i++) {
55+
if (values[i] == null) {
56+
values[i] = "null";
57+
} else if (values[i].equals("null")) {
58+
values[i] = "\"null\"";
59+
}
60+
}
61+
62+
// convert to CSV
63+
csvPrinter.println(values);
64+
65+
// as the resulting string has \r\n at the end, we will trim that away
66+
return stringWriter.toString().trim();
67+
}
68+
69+
// ======================================================
70+
// static parsers
71+
// ======================================================
72+
73+
/**
74+
* Parses the given String according to the default CSV strategy.
75+
*
76+
* @param s CSV String to be parsed.
77+
* @return parsed String matrix (which is never null)
78+
* @throws IOException in case of error
79+
* @see #setStrategy()
80+
*/
81+
public static String[][] parse(String s) throws IOException {
82+
if (s == null) {
83+
throw new IllegalArgumentException("Null argument not allowed.");
84+
}
85+
String[][] result = (new CSVParser(new StringReader(s))).getAllValues();
86+
if (result == null) {
87+
// since CSVStrategy ignores empty lines an empty array is returned
88+
// (i.e. not "result = new String[][] {{""}};")
89+
result = new String[0][0];
90+
}
91+
return result;
92+
}
93+
94+
/**
95+
* Parses the first line only according to the default CSV strategy.
96+
*
97+
* Parsing empty string will be handled as valid records containing zero
98+
* elements, so the following property holds: parseLine("").length == 0.
99+
*
100+
* @param s CSV String to be parsed.
101+
* @return parsed String vector (which is never null)
102+
* @throws IOException in case of error
103+
* @see #setStrategy()
104+
*/
105+
public static String[] parseLine(String s) throws IOException {
106+
if (s == null) {
107+
throw new IllegalArgumentException("Null argument not allowed.");
108+
}
109+
// uh,jh: make sure that parseLine("").length == 0
110+
if (s.length() == 0) {
111+
return new String[0];
112+
}
113+
return (new CSVParser(new StringReader(s))).getLine();
114+
}
115+
116+
}

0 commit comments

Comments
 (0)