]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - org/argeo/util/CsvWriter.java
1 package org
.argeo
.util
;
3 import java
.io
.IOException
;
4 import java
.io
.OutputStream
;
5 import java
.io
.PrintWriter
;
6 import java
.util
.Iterator
;
9 import org
.argeo
.ArgeoException
;
11 /** Write in CSV format. */
12 public class CsvWriter
{
13 private final PrintWriter out
;
15 private char separator
= ',';
16 private char quote
= '\"';
19 * Creates a CSV writer. The header will be written immediately to the
23 * the stream to write to. Caller is responsible for closing it.
25 public CsvWriter(OutputStream out
) {
27 this.out
= new PrintWriter(out
);
31 * Write a CSV line. Also used to write a header if needed (this is
32 * transparent for the CSV writer): simply call it first, before writing the
35 public void writeLine(List
<?
> tokens
) {
37 Iterator
<?
> it
= tokens
.iterator();
38 while (it
.hasNext()) {
39 writeToken(it
.next().toString());
45 } catch (IOException e
) {
46 throw new ArgeoException("Could not write " + tokens
, e
);
50 protected void writeToken(String token
) throws IOException
{
51 // +2 for possible quotes, another +2 assuming there would be an already
52 // quoted string where quotes needs to be duplicated
53 // another +2 for safety
54 StringBuffer buf
= new StringBuffer(token
.length() + 6);
55 char[] arr
= token
.toCharArray();
56 boolean shouldQuote
= false;
75 if (shouldQuote
== true)
77 out
.print(buf
.toString());
78 if (shouldQuote
== true)