1 package org
.argeo
.util
;
3 import java
.io
.IOException
;
4 import java
.io
.OutputStream
;
5 import java
.io
.OutputStreamWriter
;
6 import java
.io
.UnsupportedEncodingException
;
8 import java
.util
.Iterator
;
11 /** Write in CSV format. */
12 public class CsvWriter
{
13 private final Writer out
;
15 private char separator
= ',';
16 private char quote
= '\"';
19 * Creates a CSV writer.
22 * the stream to write to. Caller is responsible for closing it.
24 public CsvWriter(OutputStream out
) {
25 this.out
= new OutputStreamWriter(out
);
29 * Creates a CSV writer.
32 * the stream to write to. Caller is responsible for closing it.
34 public CsvWriter(OutputStream out
, String encoding
) {
36 this.out
= new OutputStreamWriter(out
, encoding
);
37 } catch (UnsupportedEncodingException e
) {
38 throw new UtilsException("Cannot initialize CSV writer", e
);
43 * Write a CSV line. Also used to write a header if needed (this is
44 * transparent for the CSV writer): simply call it first, before writing the
47 public void writeLine(List
<?
> tokens
) {
49 Iterator
<?
> it
= tokens
.iterator();
50 while (it
.hasNext()) {
51 writeToken(it
.next().toString());
57 } catch (IOException e
) {
58 throw new UtilsException("Could not write " + tokens
, e
);
63 * Write a CSV line. Also used to write a header if needed (this is
64 * transparent for the CSV writer): simply call it first, before writing the
67 public void writeLine(Object
[] tokens
) {
69 for (int i
= 0; i
< tokens
.length
; i
++) {
70 if (tokens
[i
] == null) {
71 // TODO configure how to deal with null
74 writeToken(tokens
[i
].toString());
76 if (i
!= (tokens
.length
- 1))
81 } catch (IOException e
) {
82 throw new UtilsException("Could not write " + tokens
, e
);
86 protected void writeToken(String token
) throws IOException
{
87 // +2 for possible quotes, another +2 assuming there would be an already
88 // quoted string where quotes needs to be duplicated
89 // another +2 for safety
90 // we don't want to increase buffer size while writing
91 StringBuffer buf
= new StringBuffer(token
.length() + 6);
92 char[] arr
= token
.toCharArray();
93 boolean shouldQuote
= false;
112 if (shouldQuote
== true)
114 out
.write(buf
.toString());
115 if (shouldQuote
== true)
119 public void setSeparator(char separator
) {
120 this.separator
= separator
;
123 public void setQuote(char quote
) {