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
}
}
}
}
|
54055(+87) Besucher