CSV-Reader und CSV-Writer

Auch verfügbar unter: http://java-csvreader-and-csvwriter.sourceforge.net

Lesen von CSV Daten aus Dateien und Streams:

Diese Klasse kann CSV Daten aus Datein und Streams lesen. Dabei werden beliebige Trennzeichen (nicht nur Komma und Semikolon) unterstützt, sowie Textkennzeichen jeder Art oder ohne. Es ist auch möglich das Textkennzeichen innerhalb der Texte zu escapen und Zeilenbrüche darin zu verwenden (default) oder dies zu unterbinden. Sind nicht alle Zeilen mit der gleichen Anzahl an Daten gefüllt kann dies ignoriert oder unterbunden werden (default):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
package de.soderer.utilities;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * The Class CsvReader.
 */

public class CsvReader implements Closeable {
  
  /**  UTF-8 BOM (Byte Order Mark) character for readers. */
  public static final char BOM_UTF_8_CHAR = (char) 65279;
  
  /**  UTF-8 BOM (Byte Order Mark) at data start (EF BB BF, ""). */
  public static final byte[] BOM_UTF_8 = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
  
  /**  UTF-16 BOM (Byte Order Mark) big endian at data start (FE FF, "þÿ"). */
  public static final byte[] BOM_UTF_16_BIG_ENDIAN = new byte[]{(byte) 0xFE, (byte) 0xFF};
  
  /**  UTF-16 BOM (Byte Order Mark) low  endian at data start (FF FE, "ÿþ"). */
  public static final byte[] BOM_UTF_16_LOW_ENDIAN = new byte[]{(byte) 0xFF, (byte) 0xFE};
  
  /** The Constant DEFAULT_ENCODING. */
  public static final String DEFAULT_ENCODING = "UTF-8";
  
  /** The Constant DEFAULT_SEPARATOR. */
  public static final char DEFAULT_SEPARATOR = ',';
  
  /** The Constant DEFAULT_STRING_QUOTE. */
  public static final char DEFAULT_STRING_QUOTE = '"';
  
  /** Mandatory separating charactor. */
  private char separator;
  
  /** Character for stringquotes: if set to null, no quoting will be done. */
  private char stringQuote;
  
  /**
   * Character to escape the stringquote character within quoted strings.
   * By default this is the stringquote character itself, so it is doubled in quoted string, but may also be a backslash '\'.
   */

  private char stringQuoteEscapeCharacter;
  
  /** Since stringQuote is a simple char this activates or deactivates the quoting. */
  private boolean useStringQuote;
  
  /** Inputstream for data. */
  private InputStream inputStream;
  
  /** Encoding of data. */
  private Charset encoding;
  
  /** Allow linebreaks in data texts without the effect of a new data set line. */
  private boolean lineBreakInDataAllowed = true;
  
  /** Allow double stringquotes to use it as a character in data text. */
  private boolean escapedStringQuoteInDataAllowed = true;
  
  /** If a single read was done, it is impossible to make a full read at once with readAll(). */
  private boolean singleReadStarted = false;
  
  /** Number of columns expected (set by first read line). */
  private int numberOfColumns = -1;
  
  /** Data reader. */
  private BufferedReader inputReader = null;
  
  /** Number of lines read until now. */
  private int readLines = 0;
  
  /** Number of chracters read until now. */
  private int readCharacters = 0;
  
  /** Allow lines with less than the expected number of data entries per line. */
  private boolean fillMissingTrailingColumnsWithNull = false;

  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   */

  public CsvReader(InputStream inputStream) {
    this(inputStream, Charset.forName(DEFAULT_ENCODING), DEFAULT_SEPARATOR, DEFAULT_STRING_QUOTE);
  }

  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param encoding the encoding
   */

  public CsvReader(InputStream inputStream, String encoding) {
    this(inputStream, Charset.forName(encoding), DEFAULT_SEPARATOR, DEFAULT_STRING_QUOTE);
  }
  
  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param encoding the encoding
   */

  public CsvReader(InputStream inputStream, Charset encoding) {
    this(inputStream, encoding, DEFAULT_SEPARATOR, DEFAULT_STRING_QUOTE);
  }
  
  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param separator the separator
   */

  public CsvReader(InputStream inputStream, char separator) {
    this(inputStream, Charset.forName(DEFAULT_ENCODING), separator, DEFAULT_STRING_QUOTE);
  }
  
  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param encoding the encoding
   * @param separator the separator
   */

  public CsvReader(InputStream inputStream, String encoding, char separator) {
    this(inputStream, Charset.forName(encoding), separator, DEFAULT_STRING_QUOTE);
  }
  
  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param encoding the encoding
   * @param separator the separator
   */

  public CsvReader(InputStream inputStream, Charset encoding, char separator) {
    this(inputStream, encoding, separator, DEFAULT_STRING_QUOTE);
  }

  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param separator the separator
   * @param stringQuote the string quote
   */

  public CsvReader(InputStream inputStream, char separator, Character stringQuote) {
    this(inputStream, Charset.forName(DEFAULT_ENCODING), separator, stringQuote);
  }

  /**
   * CSV Reader derived constructor.
   *
   * @param inputStream the input stream
   * @param encoding the encoding
   * @param separator the separator
   * @param stringQuote the string quote
   */

  public CsvReader(InputStream inputStream, String encoding, char separator, Character stringQuote) {
    this(inputStream, Charset.forName(encoding), separator, stringQuote);
  }
  
  /**
   * CSV Reader main constructor.
   *
   * @param inputStream the input stream
   * @param encoding the encoding
   * @param separator the separator
   * @param stringQuote the string quote
   */

  public CsvReader(InputStream inputStream, Charset encoding, char separator, Character stringQuote) {
    this.inputStream = inputStream;
    this.encoding = encoding;
    this.separator = separator;
    if (stringQuote != null) {
      this.stringQuote = stringQuote;
      stringQuoteEscapeCharacter = stringQuote;
      this.useStringQuote = true;
    } else {
      this.useStringQuote = false;
    }
    
    if (this.encoding == null) {
      throw new IllegalArgumentException("Encoding is null");
    } else if (this.inputStream == null) {
      throw new IllegalArgumentException("InputStream is null");
    } else if (anyCharsAreEqual(this.separator, '\r', '\n')) {
      throw new IllegalArgumentException("Separator '" + this.separator + "' is invalid");
    } else if (useStringQuote && anyCharsAreEqual(this.separator, this.stringQuote, '\r', '\n')) {
      throw new IllegalArgumentException("Stringquote '" + this.stringQuote + "' is invalid");
    }
  }
  
  /**
   * Getter for property fillMissingTrailingColumnsWithNull.
   *
   * @return true, if is fill missing trailing columns with null
   */

  public boolean isFillMissingTrailingColumnsWithNull() {
    return fillMissingTrailingColumnsWithNull;
  }

  /**
   * Setter for property fillMissingTrailingColumnsWithNull.
   *
   * @param fillMissingTrailingColumnsWithNull the new fill missing trailing columns with null
   */

  public void setFillMissingTrailingColumnsWithNull(boolean fillMissingTrailingColumnsWithNull) {
    this.fillMissingTrailingColumnsWithNull = fillMissingTrailingColumnsWithNull;
  }

  /**
   * Setter for property stringQuoteEscapeCharacter.
   * Character to escape the stringquote character within quoted strings.
   * By default this is the stringquote character itself, so it is doubled in quoted string, but may also be a backslash '\'.
   *
   * @param stringQuoteEscapeCharacter the new fill missing trailing columns with null
   */

  public void setStringQuoteEscapeCharacter(char stringQuoteEscapeCharacter) {
    this.stringQuoteEscapeCharacter = stringQuoteEscapeCharacter;
    if (useStringQuote && anyCharsAreEqual(this.separator, this.stringQuote, '\r', '\n', stringQuoteEscapeCharacter)) {
      throw new IllegalArgumentException("Stringquote escape character '" + this.stringQuoteEscapeCharacter + "' is invalid");
    }
  }
  
  /**
   * Read the next line of csv data.
   *
   * @return the list
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws CsvDataException the csv data exception
   */

  public List<String> readNextCsvLine() throws IOException, CsvDataException {
    if (inputReader == null) {
      if (inputStream == null) {
        throw new IllegalStateException("CsvReader is already closed");
      }
      inputReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
    }
    
    readLines++;
    singleReadStarted = true;
    List<String> returnList = new ArrayList<String>();
    StringBuilder nextValue = new StringBuilder();
    boolean insideString = false;
    int nextCharInt = -1;
    int previousCharInt = -1;
    
    while ((nextCharInt = inputReader.read()) != -1) {
      // Check for UTF-8 BOM at data start
      if (readCharacters == 0 && encoding == Charset.forName("UTF-8") && nextCharInt == BOM_UTF_8_CHAR) {
        continue;
      }
      
      readCharacters++;
      char nextChar = (char) nextCharInt;
      if (useStringQuote && nextChar == stringQuote) {
        if (stringQuoteEscapeCharacter != stringQuote) {
          if (previousCharInt != stringQuoteEscapeCharacter) {
            insideString = !insideString;
          }
        } else {
          insideString = !insideString;
        }
        nextValue.append(nextChar);
      } else if (!insideString) {
        if (nextChar == '\r' || nextChar == '\n') {
          if (nextValue.length() > 0 || previousCharInt == separator) {
            returnList.add(parseValue(nextValue.toString()));
          }
          
          if (returnList.size() > 0) {
            if (numberOfColumns != -1 && numberOfColumns != returnList.size()) {
              if (numberOfColumns > returnList.size() && fillMissingTrailingColumnsWithNull) {
                while (returnList.size() < numberOfColumns) {
                  returnList.add(null);
                }
              } else {
                throw new CsvDataException("Inconsistent number of values in line " + readLines + " (expected: " + numberOfColumns + " actually: " + returnList.size() + ")", readLines);
              }
            }
            numberOfColumns = returnList.size();
            return returnList;
          }
        } else if (nextChar == separator) {
          returnList.add(parseValue(nextValue.toString()));
          nextValue = new StringBuilder();
        } else {
          nextValue.append(nextChar);
        }
      } else { // insideString
        if ((nextChar == '\r' || nextChar == '\n') && !lineBreakInDataAllowed) {
          throw new CsvDataException("Not allowed linebreak in data in line " + readLines, readLines);
        } else {
          nextValue.append(nextChar);
        }
      }
      
      previousCharInt = nextCharInt;
    }
    
    if (insideString) {
      close();
      throw new IOException("Unexpected end of data after quoted csv-value was started");
    } else {
      if (nextValue.length() > 0 || previousCharInt == separator) {
        returnList.add(parseValue(nextValue.toString()));
      }
    
      if (returnList.size() > 0) {
        if (numberOfColumns != -1 && numberOfColumns != returnList.size()) {
          if (numberOfColumns > returnList.size() && fillMissingTrailingColumnsWithNull) {
            while (returnList.size() < numberOfColumns) {
              returnList.add(null);
            }
          } else {
            throw new CsvDataException("Inconsistent number of values in line " + readLines + " (expected: " + numberOfColumns + " actually: " + returnList.size() + ")", readLines);
          }
        }
        numberOfColumns = returnList.size();
        return returnList;
      } else {
        close();
        return null;
      }
    }
  }
  
  /**
   * Read all csv data at once. This can only be done before readNextCsvLine() was called for the first time
   *
   * @return the list
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws CsvDataException the csv data exception
   */

  public List<List<String>> readAll() throws IOException, CsvDataException {
    if (singleReadStarted) {
      throw new IllegalStateException("Single readNextCsvLine was called before readAll");
    }
    
    try {
      List<List<String>> csvValues = new ArrayList<List<String>>();
      List<String> lineValues;
      while ((lineValues = readNextCsvLine()) != null) {
        csvValues.add(lineValues);
      }
      return csvValues;
    } finally {
      close();
    }
  }
  
  /**
   * Parse a single value to applicate allowed double stringquotes.
   *
   * @param rawValue the raw value
   * @return the string
   * @throws CsvDataException the csv data exception
   */

  private String parseValue(String rawValue) throws CsvDataException {
    String returnValue = rawValue;
    String stringQuoteString = Character.toString(stringQuote);
    
    if (isNotEmpty(returnValue)) {
      if (useStringQuote) {
        if (returnValue.contains(stringQuoteString)) {
          returnValue = returnValue.trim();
        }
        if (returnValue.charAt(0) == stringQuote
          && returnValue.charAt(returnValue.length() - 1) == stringQuote) {
          returnValue = returnValue.substring(1, returnValue.length() - 1);
          returnValue = returnValue.replace(stringQuoteEscapeCharacter + stringQuoteString, stringQuoteString);
        }
      }
      returnValue = returnValue.replace("\r\n", "\n").replace('\r', '\n');
    }
    
    if (!escapedStringQuoteInDataAllowed && returnValue.indexOf(stringQuote) >= 0) {
      throw new CsvDataException("Not allowed stringquote in data in line " + readLines, readLines);
    }

    return returnValue;
  }

  /**
   * CLose this reader and its underlying stream.
   */

  @Override
  public void close() {
    closeQuietly(inputReader);
    inputReader = null;
    closeQuietly(inputStream);
    inputStream = null;
  }

  /**
   * Get lines read until now.
   *
   * @return the read lines
   */

  public int getReadLines() {
    return readLines;
  }
  
  /**
   * Get characters read until now.
   *
   * @return the read chracters
   */

  public int getReadChracters() {
    return readCharacters;
  }

  /**
   * Getter for property lineBreakInDataAllowed.
   *
   * @return true, if is line break in data allowed
   */

  public boolean isLineBreakInDataAllowed() {
    return lineBreakInDataAllowed;
  }

  /**
   * Setter for property lineBreakInDataAllowed.
   *
   * @param lineBreakInDataAllowed the new line break in data allowed
   */

  public void setLineBreakInDataAllowed(boolean lineBreakInDataAllowed) {
    this.lineBreakInDataAllowed = lineBreakInDataAllowed;
  }

  /**
   * Getter for property escapedStringQuoteInDataAllowed.
   *
   * @return true, if is escaped string quote in data allowed
   */

  public boolean isEscapedStringQuoteInDataAllowed() {
    return escapedStringQuoteInDataAllowed;
  }

  /**
   * Setter for property escapedStringQuoteInDataAllowed.
   *
   * @param escapedStringQuoteInDataAllowed the new escaped string quote in data allowed
   */

  public void setEscapedStringQuoteInDataAllowed(boolean escapedStringQuoteInDataAllowed) {
    this.escapedStringQuoteInDataAllowed = escapedStringQuoteInDataAllowed;
  }
  
  /**
   * This method reads the stream to the end and counts all csv value lines,
   * which can be less than the absolute linebreak count of the stream for the reason of quoted linebreaks.
   * The result also contains the first line, which may consist of columnheaders.
   *
   * @return the csv line count
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws CsvDataException the csv data exception
   */

  public int getCsvLineCount() throws IOException, CsvDataException {
    if (singleReadStarted) {
      throw new IllegalStateException("Single readNextCsvLine was called before getCsvLineCount");
    }
    
    try {
      int csvLineCount = 0;
      while (readNextCsvLine() != null) {
        csvLineCount++;
      }
      return csvLineCount;
    } finally {
      close();
    }
  }
  
  /**
   * Parse a single csv data line for data entries.
   *
   * @param separator the separator
   * @param stringQuote the string quote
   * @param csvLine the csv line
   * @return the list
   * @throws Exception the exception
   */

  public static List<String> parseCsvLine(char separator, Character stringQuote, String csvLine) throws Exception {
    CsvReader reader = null;
    try {
      reader = new CsvReader(new ByteArrayInputStream(csvLine.getBytes("UTF-8")), "UTF-8", separator, stringQuote);
      List<List<String>> fullData = reader.readAll();
      if (fullData.size() != 1) {
        throw new Exception("Too many csv lines in data");
      } else {
        return fullData.get(0);
      }
    } catch (CsvDataException e) {
      throw e;
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
  }

  /**
   * Check if any characters in a list are equal.
   *
   * @param values the values
   * @return true, if successful
   */

  private static boolean anyCharsAreEqual(char... values) {
    for (int i = 0; i < values.length; i++) {
      for (int j = i + 1; j < values.length; j++) {
        if (values[i] == values[j]) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Check if String value is not null and has a length greater than 0.
   *
   * @param value the value
   * @return true, if is not empty
   */

  private static boolean isNotEmpty(String value) {
    return value != null && value.length() > 0;
  }

  /**
   * Close a Closable item and ignore any Exception thrown by its close method.
   *
   * @param closeableItem the closeable item
   */

  private static void closeQuietly(Closeable closeableItem) {
    if (closeableItem != null) {
      try {
        closeableItem.close();
      } catch (IOException e) {
        // Do nothing
      }
    }
  }
}

Schreiben von CSV Daten in Dateien und Streams:

Diese Klasse kann CSV Daten in Datein und Streams schreiben. Dabei werden beliebige Trennzeichen (nicht nur Komma und Semikolon) unterstützt, sowie Textkennzeichen jeder Art oder ohne.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package de.soderer.utilities;

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

/**
 * The Class CsvWriter.
 */

public class CsvWriter extends Writer {
  
  /** Default output encoding. */
  public static final String DEFAULT_ENCODING = "UTF-8";
  
  /** Default output separator. */
  public static final char DEFAULT_SEPARATOR = ',';
  
  /** Default output stringquote. */
  public static final char DEFAULT_STRING_QUOTE = '"';
  
  /** Default output linebreak. */
  public static final String DEFAULT_LINEBREAK = "\n";
  
  /** Current output separator. */
  private char separator;
  
  /** Current output separator as string. */
  private String separatorString;
  
  /** Current output string quote. */
  private char stringQuote;
  
  /**
   * Character to escape the stringquote character within quoted strings.
   * By default this is the stringquote character itself, so it is doubled in quoted string, but may also be a backslash '\'.
   */

  private char stringQuoteEscapeCharacter;
  
  /** Current output string quote as string for internal use. */
  private String stringQuoteString;
  
  /** Current output string quote two times for internal use. */
  private String escapedStringQuoteString;
  
  /** Currently use the string quote. */
  private boolean useStringQuote;
  
  /** Current output linebreak. */
  private String lineBreak;
  
  /** Output stream. */
  private OutputStream outputStream;
  
  /** Output encoding. */
  private Charset encoding;
  
  /** Always quote all data entries. */
  private boolean alwaysQuote = false;
  
  /** Always quote texts or only quote them when they contain linebreaks or the separator character. */
  private boolean quoteAllStrings = false;
  
  /** Lines written until now. */
  private int writtenLines = 0;
  
  /** Number of columns to write, set by first line written. */
  private int numberOfColumns = -1;
  
  /** Output writer. */
  private BufferedWriter outputWriter = null;

  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   */

  public CsvWriter(OutputStream outputStream) {
    this(outputStream, Charset.forName(DEFAULT_ENCODING), DEFAULT_SEPARATOR, DEFAULT_STRING_QUOTE, DEFAULT_LINEBREAK);
  }

  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   */

  public CsvWriter(OutputStream outputStream, String encoding) {
    this(outputStream, Charset.forName(encoding), DEFAULT_SEPARATOR, DEFAULT_STRING_QUOTE, DEFAULT_LINEBREAK);
  }
  
  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   */

  public CsvWriter(OutputStream outputStream, Charset encoding) {
    this(outputStream, encoding, DEFAULT_SEPARATOR, DEFAULT_STRING_QUOTE, DEFAULT_LINEBREAK);
  }
  
  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param separator the separator
   */

  public CsvWriter(OutputStream outputStream, char separator) {
    this(outputStream, Charset.forName(DEFAULT_ENCODING), separator, DEFAULT_STRING_QUOTE, DEFAULT_LINEBREAK);
  }
  
  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   * @param separator the separator
   */

  public CsvWriter(OutputStream outputStream, String encoding, char separator) {
    this(outputStream, Charset.forName(encoding), separator, DEFAULT_STRING_QUOTE, DEFAULT_LINEBREAK);
  }
  
  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   * @param separator the separator
   */

  public CsvWriter(OutputStream outputStream, Charset encoding, char separator) {
    this(outputStream, encoding, separator, DEFAULT_STRING_QUOTE, DEFAULT_LINEBREAK);
  }
  
  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param separator the separator
   * @param stringQuote the string quote
   */

  public CsvWriter(OutputStream outputStream, char separator, Character stringQuote) {
    this(outputStream, Charset.forName(DEFAULT_ENCODING), separator, stringQuote, DEFAULT_LINEBREAK);
  }
  
  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param separator the separator
   * @param stringQuote the string quote
   * @param lineBreak the line break
   */

  public CsvWriter(OutputStream outputStream, char separator, Character stringQuote, String lineBreak) {
    this(outputStream, Charset.forName(DEFAULT_ENCODING), separator, stringQuote, lineBreak);
  }

  /**
   * CSV Writer derived constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   * @param separator the separator
   * @param stringQuote the string quote
   */

  public CsvWriter(OutputStream outputStream, String encoding, char separator, Character stringQuote) {
    this(outputStream, isBlank(encoding) ? Charset.forName(DEFAULT_ENCODING) : Charset.forName(encoding), separator, stringQuote == null ? DEFAULT_STRING_QUOTE : stringQuote, DEFAULT_LINEBREAK);
  }

  /**
   * CSV Writer main constructor.
   *
   * @param outputStream the output stream
   * @param encoding the encoding
   * @param separator the separator
   * @param stringQuote the string quote
   * @param lineBreak the line break
   */

  public CsvWriter(OutputStream outputStream, Charset encoding, char separator, Character stringQuote, String lineBreak) {
    this.outputStream = outputStream;
    this.encoding = encoding;
    this.separator = separator;
    separatorString = Character.toString(separator);
    this.lineBreak = lineBreak;
    if (stringQuote != null) {
      this.stringQuote = stringQuote;
      stringQuoteEscapeCharacter = stringQuote;
      stringQuoteString = Character.toString(stringQuote);
      escapedStringQuoteString = stringQuoteEscapeCharacter + stringQuoteString;
      this.useStringQuote = true;
    } else {
      this.useStringQuote = false;
    }
    
    if (this.encoding == null) {
      throw new IllegalArgumentException("Encoding is null");
    } else if (this.outputStream == null) {
      throw new IllegalArgumentException("OutputStream is null");
    } else if (anyCharsAreEqual(this.separator, '\r', '\n')) {
      throw new IllegalArgumentException("Separator '" + this.separator + "' is invalid");
    } else if (useStringQuote && anyCharsAreEqual(this.separator, this.stringQuote, '\r', '\n')) {
      throw new IllegalArgumentException("Stringquote '" + this.stringQuote + "' is invalid");
    } else if (!this.lineBreak.equals("\r") && !this.lineBreak.equals("\n") && !this.lineBreak.equals("\r\n")) {
      throw new IllegalArgumentException("Given linebreak is invalid");
    }
  }
  
  /**
   * Getter for property alwaysQuote.
   *
   * @return true, if is always quote
   */

  public boolean isAlwaysQuote() {
    return alwaysQuote;
  }

  /**
   * Setter for property alwaysQuote.
   *
   * @param alwaysQuote the new always quote
   */

  public void setAlwaysQuote(boolean alwaysQuote) {
    this.alwaysQuote = alwaysQuote;
    if (alwaysQuote) {
      quoteAllStrings = false;
    }
  }
  
  /**
   * Getter for property quoteAllStrings.
   *
   * @return true, if is quote all strings
   */

  public boolean isQuoteAllStrings() {
    return quoteAllStrings;
  }

  /**
   * Setter for property quoteAllStrings.
   *
   * @param quoteAllStrings the new quote all strings
   */

  public void setQuoteAllStrings(boolean quoteAllStrings) {
    this.quoteAllStrings = quoteAllStrings;
    if (quoteAllStrings) {
      alwaysQuote = false;
    }
  }

  /**
   * Setter for property stringQuoteEscapeCharacter.
   * Character to escape the stringquote character within quoted strings.
   * By default this is the stringquote character itself, so it is doubled in quoted string, but may also be a backslash '\'.
   *
   * @param stringQuoteEscapeCharacter the new fill missing trailing columns with null
   */

  public void setStringQuoteEscapeCharacter(char stringQuoteEscapeCharacter) {
    this.stringQuoteEscapeCharacter = stringQuoteEscapeCharacter;
    if (useStringQuote && anyCharsAreEqual(this.separator, this.stringQuote, '\r', '\n', stringQuoteEscapeCharacter)) {
      throw new IllegalArgumentException("Stringquote escape character '" + this.stringQuoteEscapeCharacter + "' is invalid");
    }
    escapedStringQuoteString = stringQuoteEscapeCharacter + stringQuoteString;
  }
  
  /**
   * Write a single line of data entries.
   *
   * @param values the values
   * @throws Exception the exception
   */

  public void writeValues(Object... values) throws Exception {
    writeValues(Arrays.asList(values));
  }
  
  /**
   * Write a single line of data entries.
   *
   * @param values the values
   * @throws CsvDataException the csv data exception
   * @throws IOException Signals that an I/O exception has occurred.
   */

  public void writeValues(List<? extends Object> values) throws CsvDataException, IOException {
    if (numberOfColumns != -1 && (values == null || numberOfColumns != values.size())) {
      throw new CsvDataException("Inconsistent number of values after " + writtenLines + " written lines (expected: " + numberOfColumns + " was: " + (values == null ? "null" : values.size()) + ")", writtenLines);
    }
    
    if (outputWriter == null) {
      if (outputStream == null) {
        throw new IllegalStateException("CsvWriter is already closed");
      }
      outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream, encoding));
    }
    
    boolean isFirst = true;
    for (Object value : values) {
      if (!isFirst) {
        outputWriter.write(separator);
      }
      isFirst = false;
      
      outputWriter.write(escapeValue(value));
    }
    outputWriter.write(lineBreak);

    writtenLines++;
    numberOfColumns = values.size();
  }
  
  /**
   * Write a full set of lines of data entries.
   *
   * @param valueLines the value lines
   * @throws Exception the exception
   */

  public void writeAll(List<List<? extends Object>> valueLines) throws Exception {
    for (List<? extends Object> valuesOfLine : valueLines) {
      writeValues(valuesOfLine);
    }
  }
  
  /**
   * Escape a single data entry using stringquotes as configured.
   *
   * @param value the value
   * @return the string
   * @throws CsvDataException the csv data exception
   */

  private String escapeValue(Object value) throws CsvDataException {
    String valueString = "";
    if (value != null) {
      valueString = value.toString();
    }
    
    if (alwaysQuote || (quoteAllStrings && value instanceof String) || valueString.contains(separatorString) || valueString.contains("\r") || valueString.contains("\n") || (useStringQuote && valueString.contains(stringQuoteString))) {
      if (!useStringQuote) {
        throw new CsvDataException("StringQuote was deactivated but is needed for csv-value after " + writtenLines + " written lines", writtenLines);
      } else {
        StringBuilder escapedValue = new StringBuilder();
        escapedValue.append(stringQuote);
        escapedValue.append(valueString.replace(stringQuoteString, escapedStringQuoteString));
        escapedValue.append(stringQuote);
        return escapedValue.toString();
      }
    } else {
      return valueString;
    }
  }

  /**
   * Close this writer and its underlying stream.
   */

  @Override
  public void close() {
    closeQuietly(outputWriter);
    outputWriter = null;
    closeQuietly(outputStream);
    outputStream = null;
  }
  
  /**
   * Get number of lines written until now.
   *
   * @return the written lines
   */

  public int getWrittenLines() {
    return writtenLines;
  }

  /**
   * Not supported method to write data (must implement for writer interface).
   *
   * @param cbuf the cbuf
   * @param off the off
   * @param len the len
   * @throws IOException Signals that an I/O exception has occurred.
   */

  @Override
  public void write(char[] cbuf, int off, int len) throws IOException {
    throw new IOException("Write by offset and length is not supported by " + getClass().getSimpleName());
  }

  /**
   * Flush buffered data.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */

  @Override
  public void flush() throws IOException {
    if (outputWriter != null) {
      outputWriter.flush();
    }
  }
  
  /**
   * Create a single csv line.
   *
   * @param separator the separator
   * @param stringQuote the string quote
   * @param values the values
   * @return the csv line
   */

  public static String getCsvLine(char separator, Character stringQuote, List<? extends Object> values) {
    return getCsvLine(separator, stringQuote, values.toArray());
  }
  
  /**
   * Create a single csv line.
   *
   * @param separator the separator
   * @param stringQuote the string quote
   * @param values the values
   * @return the csv line
   */

  public static String getCsvLine(char separator, Character stringQuote, Object... values) {
    StringBuilder returnValue = new StringBuilder();
    String separatorString = Character.toString(separator);
    String stringQuoteString = stringQuote == null ? "" : Character.toString(stringQuote);
    String doubleStringQuoteString = stringQuoteString + stringQuoteString;
    if (values != null) {
      for (Object value : values) {
        if (returnValue.length() > 0) {
          returnValue.append(separator);
        }
        if (value != null) {
          String valueString = value.toString();
          if (valueString.contains(separatorString) || valueString.contains("\r") || valueString.contains("\n") || valueString.contains(stringQuoteString)) {
            returnValue.append(stringQuoteString);
            returnValue.append(valueString.replace(stringQuoteString, doubleStringQuoteString));
            returnValue.append(stringQuoteString);
          } else {
            returnValue.append(valueString);
          }
        }
      }
    }
    return returnValue.toString();
  }

  /**
   * Check if any characters in a list are equal.
   *
   * @param values the values
   * @return true, if successful
   */

  private static boolean anyCharsAreEqual(char... values) {
    for (int i = 0; i < values.length; i++) {
      for (int j = i + 1; j < values.length; j++) {
        if (values[i] == values[j]) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Check if String value is null or contains only whitespace characters.
   *
   * @param value the value
   * @return true, if is blank
   */

  private static boolean isBlank(String value) {
    return value == null || value.trim().length() == 0;
  }

  /**
   * Close a Closable item and ignore any Exception thrown by its close method.
   *
   * @param closeableItem the closeable item
   */

  private static void closeQuietly(Closeable closeableItem) {
    if (closeableItem != null) {
      try {
        closeableItem.close();
      } catch (IOException e) {
        // Do nothing
      }
    }
  }
}