1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.addam.impexp.csv;
20
21 import java.io.IOException;
22 import java.io.Writer;
23
24 /**
25 * Writes CSV files according to the rules outlined on
26 * <a href="http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm#FileFormat">Creativyst</a>
27 *
28 * @author TIM3
29 * @since Jul 30, 2004
30 */
31 public class CSVPrinter {
32 private final Writer out;
33 private final boolean alwaysQuote;
34
35 public CSVPrinter(Writer out) {
36 this(out, false);
37 }
38
39 public CSVPrinter(Writer out, boolean alwaysQuote) {
40 this.out = out;
41 this.alwaysQuote = alwaysQuote;
42 }
43
44 /**
45 * writes each element in the strings array to a line in the CSV file
46 *
47 * @param strings
48 */
49 public void writeRecord(String[] strings) throws IOException {
50 StringBuffer buf = new StringBuffer();
51 for (int i = 0; i < strings.length; i++) {
52 String string = strings[i];
53 boolean first = (i > 0);
54 boolean quote = alwaysQuote ||
55 string.indexOf(',') != -1 ||
56 string.indexOf('\n') != -1 ||
57 string.startsWith(" ") ||
58 string.endsWith(" ");
59 if (first) buf.append(',');
60 if (quote) buf.append("\"");
61 buf.append(string.replaceAll("\\\"", "\"\""));
62 if (quote) buf.append("\"");
63 }
64 buf.append("\n");
65 out.write(buf.toString());
66 }
67 }