-
Notifications
You must be signed in to change notification settings - Fork 256
/
CSVFormat.java
2329 lines (2156 loc) · 81.4 KB
/
CSVFormat.java
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.csv;
import static org.apache.commons.csv.Constants.BACKSLASH;
import static org.apache.commons.csv.Constants.COMMA;
import static org.apache.commons.csv.Constants.COMMENT;
import static org.apache.commons.csv.Constants.CR;
import static org.apache.commons.csv.Constants.CRLF;
import static org.apache.commons.csv.Constants.DOUBLE_QUOTE_CHAR;
import static org.apache.commons.csv.Constants.EMPTY;
import static org.apache.commons.csv.Constants.LF;
import static org.apache.commons.csv.Constants.PIPE;
import static org.apache.commons.csv.Constants.SP;
import static org.apache.commons.csv.Constants.TAB;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Specifies the format of a CSV file and parses input.
*
* <h2>Using predefined formats</h2>
*
* <p>
* You can use one of the predefined formats:
* </p>
*
* <ul>
* <li>{@link #DEFAULT}</li>
* <li>{@link #EXCEL}</li>
* <li>{@link #INFORMIX_UNLOAD}</li>
* <li>{@link #INFORMIX_UNLOAD_CSV}</li>
* <li>{@link #MYSQL}</li>
* <li>{@link #RFC4180}</li>
* <li>{@link #ORACLE}</li>
* <li>{@link #POSTGRESQL_CSV}</li>
* <li>{@link #POSTGRESQL_TEXT}</li>
* <li>{@link #TDF}</li>
* </ul>
*
* <p>
* For example:
* </p>
*
* <pre>
* CSVParser parser = CSVFormat.EXCEL.parse(reader);
* </pre>
*
* <p>
* The {@link CSVParser} provides static methods to parse other input types, for example:
* </p>
*
* <pre>
* CSVParser parser = CSVParser.parse(file, StandardCharsets.US_ASCII, CSVFormat.EXCEL);
* </pre>
*
* <h2>Defining formats</h2>
*
* <p>
* You can extend a format by calling the {@code with} methods. For example:
* </p>
*
* <pre>
* CSVFormat.EXCEL.withNullString("N/A").withIgnoreSurroundingSpaces(true);
* </pre>
*
* <h2>Defining column names</h2>
*
* <p>
* To define the column names you want to use to access records, write:
* </p>
*
* <pre>
* CSVFormat.EXCEL.withHeader("Col1", "Col2", "Col3");
* </pre>
*
* <p>
* Calling {@link #withHeader(String...)} let's you use the given names to address values in a {@link CSVRecord}, and
* assumes that your CSV source does not contain a first record that also defines column names.
*
* If it does, then you are overriding this metadata with your names and you should skip the first record by calling
* {@link #withSkipHeaderRecord(boolean)} with {@code true}.
* </p>
*
* <h2>Parsing</h2>
*
* <p>
* You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write:
* </p>
*
* <pre>
* Reader in = ...;
* CSVFormat.EXCEL.withHeader("Col1", "Col2", "Col3").parse(in);
* </pre>
*
* <p>
* For other input types, like resources, files, and URLs, use the static methods on {@link CSVParser}.
* </p>
*
* <h2>Referencing columns safely</h2>
*
* <p>
* If your source contains a header record, you can simplify your code and safely reference columns, by using
* {@link #withHeader(String...)} with no arguments:
* </p>
*
* <pre>
* CSVFormat.EXCEL.withHeader();
* </pre>
*
* <p>
* This causes the parser to read the first record and use its values as column names.
*
* Then, call one of the {@link CSVRecord} get method that takes a String column name argument:
* </p>
*
* <pre>
* String value = record.get("Col1");
* </pre>
*
* <p>
* This makes your code impervious to changes in column order in the CSV file.
* </p>
*
* <h2>Notes</h2>
*
* <p>
* This class is immutable.
* </p>
*/
public final class CSVFormat implements Serializable {
/**
* Predefines formats.
*
* @since 1.2
*/
public enum Predefined {
/**
* @see CSVFormat#DEFAULT
*/
Default(CSVFormat.DEFAULT),
/**
* @see CSVFormat#EXCEL
*/
Excel(CSVFormat.EXCEL),
/**
* @see CSVFormat#INFORMIX_UNLOAD
* @since 1.3
*/
InformixUnload(CSVFormat.INFORMIX_UNLOAD),
/**
* @see CSVFormat#INFORMIX_UNLOAD_CSV
* @since 1.3
*/
InformixUnloadCsv(CSVFormat.INFORMIX_UNLOAD_CSV),
/**
* @see CSVFormat#MONGODB_CSV
* @since 1.7
*/
MongoDBCsv(CSVFormat.MONGODB_CSV),
/**
* @see CSVFormat#MONGODB_TSV
* @since 1.7
*/
MongoDBTsv(CSVFormat.MONGODB_TSV),
/**
* @see CSVFormat#MYSQL
*/
MySQL(CSVFormat.MYSQL),
/**
* @see CSVFormat#ORACLE
*/
Oracle(CSVFormat.ORACLE),
/**
* @see CSVFormat#POSTGRESQL_CSV
* @since 1.5
*/
PostgreSQLCsv(CSVFormat.POSTGRESQL_CSV),
/**
* @see CSVFormat#POSTGRESQL_CSV
*/
PostgreSQLText(CSVFormat.POSTGRESQL_TEXT),
/**
* @see CSVFormat#RFC4180
*/
RFC4180(CSVFormat.RFC4180),
/**
* @see CSVFormat#TDF
*/
TDF(CSVFormat.TDF);
private final CSVFormat format;
Predefined(final CSVFormat format) {
this.format = format;
}
/**
* Gets the format.
*
* @return the format.
*/
public CSVFormat getFormat() {
return format;
}
}
/**
* Standard Comma Separated Value format, as for {@link #RFC4180} but allowing empty lines.
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',')}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withRecordSeparator("\r\n")}</li>
* <li>{@code withIgnoreEmptyLines(true)}</li>
* <li>{@code withAllowDuplicateHeaderNames(true)}</li>
* </ul>
*
* @see Predefined#Default
*/
public static final CSVFormat DEFAULT = new CSVFormat(COMMA, DOUBLE_QUOTE_CHAR, null, null, null, false, true, CRLF,
null, null, null, false, false, false, false, false, false, true);
/**
* Excel file format (using a comma as the value delimiter). Note that the actual value delimiter used by Excel is
* locale dependent, it might be necessary to customize this format to accommodate to your regional settings.
*
* <p>
* For example for parsing or generating a CSV file on a French system the following format will be used:
* </p>
*
* <pre>
* CSVFormat fmt = CSVFormat.EXCEL.withDelimiter(';');
* </pre>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code {@link #withDelimiter(char) withDelimiter(',')}}</li>
* <li>{@code {@link #withQuote(char) withQuote('"')}}</li>
* <li>{@code {@link #withRecordSeparator(String) withRecordSeparator("\r\n")}}</li>
* <li>{@code {@link #withIgnoreEmptyLines(boolean) withIgnoreEmptyLines(false)}}</li>
* <li>{@code {@link #withAllowMissingColumnNames(boolean) withAllowMissingColumnNames(true)}}</li>
* <li>{@code {@link #withAllowDuplicateHeaderNames(boolean) withAllowDuplicateHeaderNames(true)}}</li>
* </ul>
* <p>
* Note: This is currently like {@link #RFC4180} plus {@link #withAllowMissingColumnNames(boolean)
* withAllowMissingColumnNames(true)} and {@link #withIgnoreEmptyLines(boolean) withIgnoreEmptyLines(false)}.
* </p>
*
* @see Predefined#Excel
*/
// @formatter:off
public static final CSVFormat EXCEL = DEFAULT
.withIgnoreEmptyLines(false)
.withAllowMissingColumnNames();
// @formatter:on
/**
* Default Informix CSV UNLOAD format used by the {@code UNLOAD TO file_name} operation.
*
* <p>
* This is a comma-delimited format with a LF character as the line separator. Values are not quoted and special
* characters are escaped with {@code '\'}. The default NULL string is {@code "\\N"}.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',')}</li>
* <li>{@code withEscape('\\')}</li>
* <li>{@code withQuote("\"")}</li>
* <li>{@code withRecordSeparator('\n')}</li>
* </ul>
*
* @see Predefined#MySQL
* @see <a href=
* "http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_InOutSql_UNLOAD.htm">
* http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_InOutSql_UNLOAD.htm</a>
* @since 1.3
*/
// @formatter:off
public static final CSVFormat INFORMIX_UNLOAD = DEFAULT
.withDelimiter(PIPE)
.withEscape(BACKSLASH)
.withQuote(DOUBLE_QUOTE_CHAR)
.withRecordSeparator(LF);
// @formatter:on
/**
* Default Informix CSV UNLOAD format used by the {@code UNLOAD TO file_name} operation (escaping is disabled.)
*
* <p>
* This is a comma-delimited format with a LF character as the line separator. Values are not quoted and special
* characters are escaped with {@code '\'}. The default NULL string is {@code "\\N"}.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',')}</li>
* <li>{@code withQuote("\"")}</li>
* <li>{@code withRecordSeparator('\n')}</li>
* </ul>
*
* @see Predefined#MySQL
* @see <a href=
* "http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_InOutSql_UNLOAD.htm">
* http://www.ibm.com/support/knowledgecenter/SSBJG3_2.5.0/com.ibm.gen_busug.doc/c_fgl_InOutSql_UNLOAD.htm</a>
* @since 1.3
*/
// @formatter:off
public static final CSVFormat INFORMIX_UNLOAD_CSV = DEFAULT
.withDelimiter(COMMA)
.withQuote(DOUBLE_QUOTE_CHAR)
.withRecordSeparator(LF);
// @formatter:on
/**
* Default MongoDB CSV format used by the {@code mongoexport} operation.
* <p>
* <b>Parsing is not supported yet.</b>
* </p>
*
* <p>
* This is a comma-delimited format. Values are double quoted only if needed and special characters are escaped with
* {@code '"'}. A header line with field names is expected.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',')}</li>
* <li>{@code withEscape('"')}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withQuoteMode(QuoteMode.ALL_NON_NULL)}</li>
* <li>{@code withSkipHeaderRecord(false)}</li>
* </ul>
*
* @see Predefined#MongoDBCsv
* @see <a href="https://docs.mongodb.com/manual/reference/program/mongoexport/">MongoDB mongoexport command
* documentation</a>
* @since 1.7
*/
// @formatter:off
public static final CSVFormat MONGODB_CSV = DEFAULT
.withDelimiter(COMMA)
.withEscape(DOUBLE_QUOTE_CHAR)
.withQuote(DOUBLE_QUOTE_CHAR)
.withQuoteMode(QuoteMode.MINIMAL)
.withSkipHeaderRecord(false);
// @formatter:off
/**
* Default MongoDB TSV format used by the {@code mongoexport} operation.
* <p>
* <b>Parsing is not supported yet.</b>
* </p>
*
* <p>
* This is a tab-delimited format. Values are double quoted only if needed and special
* characters are escaped with {@code '"'}. A header line with field names is expected.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter('\t')}</li>
* <li>{@code withEscape('"')}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withQuoteMode(QuoteMode.ALL_NON_NULL)}</li>
* <li>{@code withSkipHeaderRecord(false)}</li>
* </ul>
*
* @see Predefined#MongoDBCsv
* @see <a href="https://docs.mongodb.com/manual/reference/program/mongoexport/">MongoDB mongoexport command
* documentation</a>
* @since 1.7
*/
// @formatter:off
public static final CSVFormat MONGODB_TSV = DEFAULT
.withDelimiter(TAB)
.withEscape(DOUBLE_QUOTE_CHAR)
.withQuote(DOUBLE_QUOTE_CHAR)
.withQuoteMode(QuoteMode.MINIMAL)
.withSkipHeaderRecord(false);
// @formatter:off
/**
* Default MySQL format used by the {@code SELECT INTO OUTFILE} and {@code LOAD DATA INFILE} operations.
*
* <p>
* This is a tab-delimited format with a LF character as the line separator. Values are not quoted and special
* characters are escaped with {@code '\'}. The default NULL string is {@code "\\N"}.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter('\t')}</li>
* <li>{@code withEscape('\\')}</li>
* <li>{@code withIgnoreEmptyLines(false)}</li>
* <li>{@code withQuote(null)}</li>
* <li>{@code withRecordSeparator('\n')}</li>
* <li>{@code withNullString("\\N")}</li>
* <li>{@code withQuoteMode(QuoteMode.ALL_NON_NULL)}</li>
* </ul>
*
* @see Predefined#MySQL
* @see <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html"> http://dev.mysql.com/doc/refman/5.1/en/load
* -data.html</a>
*/
// @formatter:off
public static final CSVFormat MYSQL = DEFAULT
.withDelimiter(TAB)
.withEscape(BACKSLASH)
.withIgnoreEmptyLines(false)
.withQuote(null)
.withRecordSeparator(LF)
.withNullString("\\N")
.withQuoteMode(QuoteMode.ALL_NON_NULL);
// @formatter:off
/**
* Default Oracle format used by the SQL*Loader utility.
*
* <p>
* This is a comma-delimited format with the system line separator character as the record separator.Values are
* double quoted when needed and special characters are escaped with {@code '"'}. The default NULL string is
* {@code ""}. Values are trimmed.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',') // default is {@code FIELDS TERMINATED BY ','}}</li>
* <li>{@code withEscape('\\')}</li>
* <li>{@code withIgnoreEmptyLines(false)}</li>
* <li>{@code withQuote('"') // default is {@code OPTIONALLY ENCLOSED BY '"'}}</li>
* <li>{@code withNullString("\\N")}</li>
* <li>{@code withTrim()}</li>
* <li>{@code withSystemRecordSeparator()}</li>
* <li>{@code withQuoteMode(QuoteMode.MINIMAL)}</li>
* </ul>
*
* @see Predefined#Oracle
* @see <a href="https://s.apache.org/CGXG">Oracle CSV Format Specification</a>
* @since 1.6
*/
// @formatter:off
public static final CSVFormat ORACLE = DEFAULT
.withDelimiter(COMMA)
.withEscape(BACKSLASH)
.withIgnoreEmptyLines(false)
.withQuote(DOUBLE_QUOTE_CHAR)
.withNullString("\\N")
.withTrim()
.withSystemRecordSeparator()
.withQuoteMode(QuoteMode.MINIMAL);
// @formatter:off
/**
* Default PostgreSQL CSV format used by the {@code COPY} operation.
*
* <p>
* This is a comma-delimited format with a LF character as the line separator. Values are double quoted and special
* characters are escaped with {@code '"'}. The default NULL string is {@code ""}.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',')}</li>
* <li>{@code withEscape('"')}</li>
* <li>{@code withIgnoreEmptyLines(false)}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withRecordSeparator('\n')}</li>
* <li>{@code withNullString("")}</li>
* <li>{@code withQuoteMode(QuoteMode.ALL_NON_NULL)}</li>
* </ul>
*
* @see Predefined#MySQL
* @see <a href="https://www.postgresql.org/docs/current/static/sql-copy.html">PostgreSQL COPY command
* documentation</a>
* @since 1.5
*/
// @formatter:off
public static final CSVFormat POSTGRESQL_CSV = DEFAULT
.withDelimiter(COMMA)
.withEscape(DOUBLE_QUOTE_CHAR)
.withIgnoreEmptyLines(false)
.withQuote(DOUBLE_QUOTE_CHAR)
.withRecordSeparator(LF)
.withNullString(EMPTY)
.withQuoteMode(QuoteMode.ALL_NON_NULL);
// @formatter:off
/**
* Default PostgreSQL text format used by the {@code COPY} operation.
*
* <p>
* This is a tab-delimited format with a LF character as the line separator. Values are double quoted and special
* characters are escaped with {@code '"'}. The default NULL string is {@code "\\N"}.
* </p>
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter('\t')}</li>
* <li>{@code withEscape('\\')}</li>
* <li>{@code withIgnoreEmptyLines(false)}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withRecordSeparator('\n')}</li>
* <li>{@code withNullString("\\N")}</li>
* <li>{@code withQuoteMode(QuoteMode.ALL_NON_NULL)}</li>
* </ul>
*
* @see Predefined#MySQL
* @see <a href="https://www.postgresql.org/docs/current/static/sql-copy.html">PostgreSQL COPY command
* documentation</a>
* @since 1.5
*/
// @formatter:off
public static final CSVFormat POSTGRESQL_TEXT = DEFAULT
.withDelimiter(TAB)
.withEscape(BACKSLASH)
.withIgnoreEmptyLines(false)
.withQuote(DOUBLE_QUOTE_CHAR)
.withRecordSeparator(LF)
.withNullString("\\N")
.withQuoteMode(QuoteMode.ALL_NON_NULL);
// @formatter:off
/**
* Comma separated format as defined by <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter(',')}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withRecordSeparator("\r\n")}</li>
* <li>{@code withIgnoreEmptyLines(false)}</li>
* </ul>
*
* @see Predefined#RFC4180
*/
public static final CSVFormat RFC4180 = DEFAULT.withIgnoreEmptyLines(false);
private static final long serialVersionUID = 1L;
/**
* Tab-delimited format.
*
* <p>
* Settings are:
* </p>
* <ul>
* <li>{@code withDelimiter('\t')}</li>
* <li>{@code withQuote('"')}</li>
* <li>{@code withRecordSeparator("\r\n")}</li>
* <li>{@code withIgnoreSurroundingSpaces(true)}</li>
* </ul>
*
* @see Predefined#TDF
*/
// @formatter:off
public static final CSVFormat TDF = DEFAULT
.withDelimiter(TAB)
.withIgnoreSurroundingSpaces();
// @formatter:on
/**
* Returns true if the given character is a line break character.
*
* @param c
* the character to check
*
* @return true if {@code c} is a line break character
*/
private static boolean isLineBreak(final char c) {
return c == LF || c == CR;
}
/**
* Returns true if the given character is a line break character.
*
* @param c
* the character to check, may be null
*
* @return true if {@code c} is a line break character (and not null)
*/
private static boolean isLineBreak(final Character c) {
return c != null && isLineBreak(c.charValue());
}
/**
* Creates a new CSV format with the specified delimiter.
*
* <p>
* Use this method if you want to create a CSVFormat from scratch. All fields but the delimiter will be initialized
* with null/false.
* </p>
*
* @param delimiter
* the char used for value separation, must not be a line break character
* @return a new CSV format.
* @throws IllegalArgumentException
* if the delimiter is a line break character
*
* @see #DEFAULT
* @see #RFC4180
* @see #MYSQL
* @see #EXCEL
* @see #TDF
*/
public static CSVFormat newFormat(final char delimiter) {
return new CSVFormat(delimiter, null, null, null, null, false, false, null, null, null, null, false, false,
false, false, false, false, true);
}
/**
* Gets one of the predefined formats from {@link CSVFormat.Predefined}.
*
* @param format
* name
* @return one of the predefined formats
* @since 1.2
*/
public static CSVFormat valueOf(final String format) {
return CSVFormat.Predefined.valueOf(format).getFormat();
}
private final boolean allowDuplicateHeaderNames;
private final boolean allowMissingColumnNames;
private final boolean autoFlush;
private final Character commentMarker; // null if commenting is disabled
private final char delimiter;
private final Character escapeCharacter; // null if escaping is disabled
private final String[] header; // array of header column names
private final String[] headerComments; // array of header comment lines
private final boolean ignoreEmptyLines;
private final boolean ignoreHeaderCase; // should ignore header names case
private final boolean ignoreSurroundingSpaces; // Should leading/trailing spaces be ignored around values?
private final String nullString; // the string to be used for null values
private final Character quoteCharacter; // null if quoting is disabled
private final String quotedNullString;
private final QuoteMode quoteMode;
private final String recordSeparator; // for outputs
private final boolean skipHeaderRecord;
private final boolean trailingDelimiter;
private final boolean trim;
/**
* Creates a customized CSV format.
*
* @param delimiter
* the char used for value separation, must not be a line break character
* @param quoteChar
* the Character used as value encapsulation marker, may be {@code null} to disable
* @param quoteMode
* the quote mode
* @param commentStart
* the Character used for comment identification, may be {@code null} to disable
* @param escape
* the Character used to escape special characters in values, may be {@code null} to disable
* @param ignoreSurroundingSpaces
* {@code true} when whitespaces enclosing values should be ignored
* @param ignoreEmptyLines
* {@code true} when the parser should skip empty lines
* @param recordSeparator
* the line separator to use for output
* @param nullString
* the line separator to use for output
* @param headerComments
* the comments to be printed by the Printer before the actual CSV data
* @param header
* the header
* @param skipHeaderRecord
* TODO
* @param allowMissingColumnNames
* TODO
* @param ignoreHeaderCase
* TODO
* @param trim
* TODO
* @param trailingDelimiter
* TODO
* @param autoFlush
* @throws IllegalArgumentException
* if the delimiter is a line break character
*/
private CSVFormat(final char delimiter, final Character quoteChar, final QuoteMode quoteMode,
final Character commentStart, final Character escape, final boolean ignoreSurroundingSpaces,
final boolean ignoreEmptyLines, final String recordSeparator, final String nullString,
final Object[] headerComments, final String[] header, final boolean skipHeaderRecord,
final boolean allowMissingColumnNames, final boolean ignoreHeaderCase, final boolean trim,
final boolean trailingDelimiter, final boolean autoFlush, final boolean allowDuplicateHeaderNames) {
this.delimiter = delimiter;
this.quoteCharacter = quoteChar;
this.quoteMode = quoteMode;
this.commentMarker = commentStart;
this.escapeCharacter = escape;
this.ignoreSurroundingSpaces = ignoreSurroundingSpaces;
this.allowMissingColumnNames = allowMissingColumnNames;
this.ignoreEmptyLines = ignoreEmptyLines;
this.recordSeparator = recordSeparator;
this.nullString = nullString;
this.headerComments = toStringArray(headerComments);
this.header = header == null ? null : header.clone();
this.skipHeaderRecord = skipHeaderRecord;
this.ignoreHeaderCase = ignoreHeaderCase;
this.trailingDelimiter = trailingDelimiter;
this.trim = trim;
this.autoFlush = autoFlush;
this.quotedNullString = quoteCharacter + nullString + quoteCharacter;
this.allowDuplicateHeaderNames = allowDuplicateHeaderNames;
validate();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CSVFormat other = (CSVFormat) obj;
if (delimiter != other.delimiter) {
return false;
}
if (trailingDelimiter != other.trailingDelimiter) {
return false;
}
if (autoFlush != other.autoFlush) {
return false;
}
if (trim != other.trim) {
return false;
}
if (allowMissingColumnNames != other.allowMissingColumnNames) {
return false;
}
if (allowDuplicateHeaderNames != other.allowDuplicateHeaderNames) {
return false;
}
if (ignoreHeaderCase != other.ignoreHeaderCase) {
return false;
}
if (quoteMode != other.quoteMode) {
return false;
}
if (quoteCharacter == null) {
if (other.quoteCharacter != null) {
return false;
}
} else if (!quoteCharacter.equals(other.quoteCharacter)) {
return false;
}
if (commentMarker == null) {
if (other.commentMarker != null) {
return false;
}
} else if (!commentMarker.equals(other.commentMarker)) {
return false;
}
if (escapeCharacter == null) {
if (other.escapeCharacter != null) {
return false;
}
} else if (!escapeCharacter.equals(other.escapeCharacter)) {
return false;
}
if (nullString == null) {
if (other.nullString != null) {
return false;
}
} else if (!nullString.equals(other.nullString)) {
return false;
}
if (!Arrays.equals(header, other.header)) {
return false;
}
if (ignoreSurroundingSpaces != other.ignoreSurroundingSpaces) {
return false;
}
if (ignoreEmptyLines != other.ignoreEmptyLines) {
return false;
}
if (skipHeaderRecord != other.skipHeaderRecord) {
return false;
}
if (recordSeparator == null) {
if (other.recordSeparator != null) {
return false;
}
} else if (!recordSeparator.equals(other.recordSeparator)) {
return false;
}
if (!Arrays.equals(headerComments, other.headerComments)) {
return false;
}
return true;
}
/**
* Formats the specified values.
*
* @param values
* the values to format
* @return the formatted values
*/
public String format(final Object... values) {
final StringWriter out = new StringWriter();
try (CSVPrinter csvPrinter = new CSVPrinter(out, this)) {
csvPrinter.printRecord(values);
return out.toString().trim();
} catch (final IOException e) {
// should not happen because a StringWriter does not do IO.
throw new IllegalStateException(e);
}
}
/**
* Returns true if and only if duplicate names are allowed in the headers.
*
* @return whether duplicate header names are allowed
* @since 1.7
*/
public boolean getAllowDuplicateHeaderNames() {
return allowDuplicateHeaderNames;
}
/**
* Specifies whether missing column names are allowed when parsing the header line.
*
* @return {@code true} if missing column names are allowed when parsing the header line, {@code false} to throw an
* {@link IllegalArgumentException}.
*/
public boolean getAllowMissingColumnNames() {
return allowMissingColumnNames;
}
/**
* Returns whether to flush on close.
*
* @return whether to flush on close.
* @since 1.6
*/
public boolean getAutoFlush() {
return autoFlush;
}
/**
* Returns the character marking the start of a line comment.
*
* @return the comment start marker, may be {@code null}
*/
public Character getCommentMarker() {
return commentMarker;
}
/**
* Returns the character delimiting the values (typically ';', ',' or '\t').
*
* @return the delimiter character
*/
public char getDelimiter() {
return delimiter;
}
/**
* Returns the escape character.
*
* @return the escape character, may be {@code null}
*/
public Character getEscapeCharacter() {
return escapeCharacter;
}
/**
* Returns a copy of the header array.
*
* @return a copy of the header array; {@code null} if disabled, the empty array if to be read from the file
*/
public String[] getHeader() {
return header != null ? header.clone() : null;
}
/**
* Returns a copy of the header comment array.
*
* @return a copy of the header comment array; {@code null} if disabled.
*/
public String[] getHeaderComments() {
return headerComments != null ? headerComments.clone() : null;
}
/**
* Specifies whether empty lines between records are ignored when parsing input.
*
* @return {@code true} if empty lines between records are ignored, {@code false} if they are turned into empty
* records.
*/
public boolean getIgnoreEmptyLines() {
return ignoreEmptyLines;
}
/**
* Specifies whether header names will be accessed ignoring case.
*
* @return {@code true} if header names cases are ignored, {@code false} if they are case sensitive.
* @since 1.3
*/
public boolean getIgnoreHeaderCase() {
return ignoreHeaderCase;
}
/**
* Specifies whether spaces around values are ignored when parsing input.