]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - basic/runtime/org.argeo.basic.nodeps/src/main/java/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
);
51 * Write a CSV line. Also used to write a header if needed (this is
52 * transparent for the CSV writer): simply call it first, before writing the
55 public void writeLine(Object
[] tokens
) {
57 for (int i
= 0; i
< tokens
.length
; i
++) {
58 writeToken(tokens
[i
].toString());
59 if (i
!= (tokens
.length
- 1))
64 } catch (IOException e
) {
65 throw new ArgeoException("Could not write " + tokens
, e
);
69 protected void writeToken(String token
) throws IOException
{
70 // +2 for possible quotes, another +2 assuming there would be an already
71 // quoted string where quotes needs to be duplicated
72 // another +2 for safety
73 StringBuffer buf
= new StringBuffer(token
.length() + 6);
74 char[] arr
= token
.toCharArray();
75 boolean shouldQuote
= false;
94 if (shouldQuote
== true)
96 out
.print(buf
.toString());
97 if (shouldQuote
== true)
101 public void setSeparator(char separator
) {
102 this.separator
= separator
;
105 public void setQuote(char quote
) {