KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jutils > csv > CSVWriter


1 /*------------------------------------------------------------------------------
2 Name: CSVWriter.java
3 Project: jutils.org
4 Comment: writes CSV (Comma Separated Value) files
5 Version: $Id: CSVWriter.java,v 1.2 2004/04/07 08:04:24 laurent Exp $
6 Author: Roedy Green roedy@mindprod.com, Heinrich Goetzger goetzger@gmx.net
7 ------------------------------------------------------------------------------*/

8 package org.jutils.csv;
9
10 import java.io.EOFException JavaDoc;
11 import java.io.FileWriter JavaDoc;
12 import java.io.IOException JavaDoc;
13 import java.io.PrintWriter JavaDoc;
14 import java.io.Writer JavaDoc;
15
16 /**
17  * Writes CSV (Comma Separated Value) files.
18  *
19  * This format is mainly used my Microsoft Word and Excel.
20  * Fields are separated by commas, and enclosed in
21  * quotes if they contain commas or quotes.
22  * Embedded quotes are doubled.
23  * Embedded spaces do not normally require surrounding quotes.
24  * The last field on the line is not followed by a comma.
25  * Null fields are represented by two commas in a row.
26  *
27  * @author copyright (c) 2002 Roedy Green Canadian Mind Products
28  * Roedy posted this code on Newsgroups:comp.lang.java.programmer on 27th March 2002.
29  *
30  * Heinrich added some stuff like comment ability and linewise working.
31  *
32  */

33 public class CSVWriter {
34
35    /**
36     * Constructor
37     *
38     * @param pw PrintWriter where fields will be written.
39     * @param forceQuotes
40     * true if you want all fields surrounded in quotes,
41     * whether or not they contain commas, quotes or spaces.
42     * @param separator
43     * field separator character, usually ',' in North America,
44     * ';' in Europe and sometimes '\t' for tab.
45     * @param lineSeparator
46     * gives the delimiter for the line; is per default set to
47     * the system property 'line.separator'
48     */

49    public CSVWriter(PrintWriter JavaDoc pw, boolean forceQuotes, char separator, String JavaDoc lineSeparator) {
50       this.pw = pw;
51       this.forceQuotes = forceQuotes;
52       this.separator = separator;
53       this.comment = "# ";
54       this.lineSeparator = lineSeparator;
55    } // end of CSVWriter
56

57    public CSVWriter(Writer JavaDoc w, boolean forceQuotes, char separator, String JavaDoc lineSeparator) {
58        this(new PrintWriter JavaDoc(w),forceQuotes,separator,lineSeparator);
59    }
60
61    /**
62     * Constructor with default field separator ','.
63     *
64     * @param pw PrintWriter where fields will be written.
65     */

66    public CSVWriter(PrintWriter JavaDoc pw) {
67       this.pw = pw;
68       this.forceQuotes = false;
69       this.separator = ',';
70       this.comment = "# ";
71       this.lineSeparator = System.getProperty("line.separator");
72    } // end of CSVWriter
73

74     
75    public CSVWriter(Writer JavaDoc w) {
76        this(new PrintWriter JavaDoc(w));
77    }
78
79    /**
80     * Constructor with default field separator ','.
81     *
82     * @param pw PrintWriter where fields will be written.
83     * @param comment Character used to start a comment line
84     */

85    public CSVWriter(PrintWriter JavaDoc pw, char comment) {
86       this.pw = pw;
87       this.forceQuotes = false;
88       this.separator = ',';
89       this.comment = String.valueOf(comment) + " ";
90       this.lineSeparator = System.getProperty("line.separator");
91    } // end of CSVWriter
92

93    public CSVWriter(Writer JavaDoc w, char comment) {
94        this(new PrintWriter JavaDoc(w),comment);
95    }
96
97    /**
98     * PrintWriter where CSV fields will be written.
99     */

100    PrintWriter JavaDoc pw;
101
102    /**
103     * true if you want all fields surrounded in quotes,
104     * whether or not they contain commas, quotes or spaces.
105     */

106    boolean forceQuotes;
107
108    /*
109     * field separator character, usually ',' in North America,
110     * ';' in Europe and sometimes '\t' for tab.
111     */

112    char separator;
113
114    /**
115     * true if there has was a field previously written to
116     * this line, meaning there is a comma pending to
117     * be written.
118     */

119    boolean wasPreviousField = false;
120
121    /**
122     * Character to start a comment line with. May be '#' for example.
123     */

124    String JavaDoc comment;
125
126    /**
127     * Line separator.
128     */

129    String JavaDoc lineSeparator;
130
131    /**
132     * Writes a single coment line to the file given by the <code>text</code>.
133     * This is the text leaded by the <code>comment char + " "</code>, given in the constructor.
134     * @param text contains the comment text.
135     */

136    public void writeCommentln(String JavaDoc text) {
137       if (wasPreviousField) writeln(); // close open line since we need to start a new one for comment
138
pw.print(comment);
139       //wasPreviousField = false; // to prevent a comma after the comment sign
140
write(text);
141       writeln();
142    } // end of writeComentln
143

144    /**
145     * Writes a single value in a line suited by a newline to the file given by the <code>token</code>.
146     * @param token contains the value.
147     */

148    public void writeln(String JavaDoc token) {
149       write(token);
150       writeln();
151    } // end of writeln
152

153    /**
154     * Writes a new line in the CVS output file to demark the end of record.
155     */

156    public void writeln() {
157       /* don't bother to write last pending comma on the line */
158       wasPreviousField = false;
159       pw.print(lineSeparator);
160    } // end of writeln
161

162    /**
163     * Writes a single line of comma separated values from the array given by <code>line</code>.
164     * @param line containig an array of tokens.
165     */

166    public void writeln(String JavaDoc[] line) {
167       for(int ii=0; ii < line.length; ii++) {
168          write(line[ii]);
169       } // end of for
170

171       writeln(); // write newLine
172

173    } // end of writeln
174

175    /**
176      * Write one csv field to the file, followed by a separator
177      * unless it is the last field on the line. Lead and trailing
178      * blanks will be removed.
179      *
180      * @param s The string to write. Any additional quotes or
181      * embedded quotes will be provided by write.
182      */

183    public void write(String JavaDoc s) {
184       if ( wasPreviousField ) {
185          pw.print(separator);
186       }
187
188       if ( s == null ) {
189          pw.print("");
190          return;
191       } // end of if s == null
192

193       s = s.trim();
194       if ( s.indexOf('\"') >= 0 ) {
195          /* worst case, needs surrounding quotes and internal quotes doubled */
196          pw.print ('\"');
197          for ( int i=0; i<s.length(); i++ ) {
198             char c = s.charAt(i);
199             if ( c == '\"' ) {
200                pw.print("\"\"");
201             } else {
202                pw.print(c);
203             }
204          }
205          pw.print ('\"');
206          // end of if \"
207
} else if ( s.indexOf('\n') >=0 ) {
208          // bad case as well: having a new line in the token: \n
209
pw.print ('\"');
210          for ( int i=0; i<s.length(); i++ ) {
211             char c = s.charAt(i);
212             if ( c == '\n' ) {
213                pw.print("\\n");
214             } else {
215                pw.print(c);
216             }
217          }
218          pw.print ('\"');
219          // end of if \n
220
} else if ( forceQuotes || s.indexOf(separator) >= 0 ) {
221          /* need surrounding quotes */
222          pw.print ('\"');
223          pw.print(s);
224          pw.print ('\"');
225       } else {
226          /* ordinary case, no surrounding quotes needed */
227          pw.print(s);
228       }
229       /* make a note to print trailing comma later */
230       wasPreviousField = true;
231    } // end of write
232

233    /**
234     * Close the PrintWriter.
235     */

236    public void close() {
237       if ( pw != null ) {
238          pw.close();
239          pw = null;
240       } // end of if
241
} // end of close
242

243    /**
244     * Test driver
245     *
246     * @param args [0]: The name of the file.
247     */

248    static public void main(String JavaDoc[] args) {
249       try {
250          // write out a test file
251
PrintWriter JavaDoc pw = new PrintWriter JavaDoc( new FileWriter JavaDoc(args[0]));
252          CSVWriter csv = new CSVWriter(pw, false, ',', System.getProperty("line.separator") );
253          csv.writeCommentln("This is a test csv-file: '" + args[0] + "'");
254          csv.write("abc");
255          csv.write("def");
256          csv.write("g h i");
257          csv.write("jk,l");
258          csv.write("m\"n\'o ");
259          csv.writeln();
260          csv.write("m\"n\'o ");
261          csv.write(" ");
262          csv.write("a");
263          csv.write("x,y,z");
264          csv.write("x;y;z");
265          csv.writeln();
266          csv.writeln(new String JavaDoc[] {"This", "is", "an", "array."});
267          csv.close();
268       } catch ( IOException JavaDoc e ) {
269          e.printStackTrace();
270          System.out.println(e.getMessage());
271       }
272    } // end main
273

274 } // end CSVWriter
275

276 // end of file
277
Popular Tags