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 import org
.argeo
.ArgeoException
;
13 /** Write in CSV format. */
14 public class CsvWriter
{
15 private final Writer out
;
17 private char separator
= ',';
18 private char quote
= '\"';
21 * Creates a CSV writer.
24 * the stream to write to. Caller is responsible for closing it.
26 public CsvWriter(OutputStream out
) {
27 this.out
= new OutputStreamWriter(out
);
31 * Creates a CSV writer.
34 * the stream to write to. Caller is responsible for closing it.
36 public CsvWriter(OutputStream out
, String encoding
) {
38 this.out
= new OutputStreamWriter(out
, encoding
);
39 } catch (UnsupportedEncodingException e
) {
40 throw new ArgeoException("Cannot initialize CSV writer", e
);
45 * Write a CSV line. Also used to write a header if needed (this is
46 * transparent for the CSV writer): simply call it first, before writing the
49 public void writeLine(List
<?
> tokens
) {
51 Iterator
<?
> it
= tokens
.iterator();
52 while (it
.hasNext()) {
53 writeToken(it
.next().toString());
59 } catch (IOException e
) {
60 throw new ArgeoException("Could not write " + tokens
, e
);
65 * Write a CSV line. Also used to write a header if needed (this is
66 * transparent for the CSV writer): simply call it first, before writing the
69 public void writeLine(Object
[] tokens
) {
71 for (int i
= 0; i
< tokens
.length
; i
++) {
72 if (tokens
[i
] == null) {
73 // TODO configure how to deal with null
76 writeToken(tokens
[i
].toString());
78 if (i
!= (tokens
.length
- 1))
83 } catch (IOException e
) {
84 throw new ArgeoException("Could not write " + tokens
, e
);
88 protected void writeToken(String token
) throws IOException
{
89 // +2 for possible quotes, another +2 assuming there would be an already
90 // quoted string where quotes needs to be duplicated
91 // another +2 for safety
92 // we don't want to increase buffer size while writing
93 StringBuffer buf
= new StringBuffer(token
.length() + 6);
94 char[] arr
= token
.toCharArray();
95 boolean shouldQuote
= false;
114 if (shouldQuote
== true)
116 out
.write(buf
.toString());
117 if (shouldQuote
== true)
121 public void setSeparator(char separator
) {
122 this.separator
= separator
;
125 public void setQuote(char quote
) {