View Javadoc
1   /*
2    Copyright 2005 Bytecode Pty Ltd.
3   
4    Licensed under the Apache License, Version 2.0 (the "License");
5    you may not use this file except in compliance with the License.
6    You may obtain a copy of the License at
7   
8    http://www.apache.org/licenses/LICENSE-2.0
9   
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15   */
16  package com.opencsv;
17  
18  
19  import com.opencsv.enums.CSVReaderNullFieldIndicator;
20  import com.opencsv.processor.RowProcessor;
21  import com.opencsv.validators.LineValidator;
22  import com.opencsv.validators.RowValidator;
23  import org.apache.commons.lang3.ObjectUtils;
24  
25  import java.io.Reader;
26  import java.util.Locale;
27  import java.util.ResourceBundle;
28  
29  /**
30   * Builder for creating a {@link CSVReader}.
31   * <p>This should be the preferred method of creating a Reader as there are so many
32   * possible values to be set it is impossible to have constructors for all of
33   * them and keep backwards compatibility with previous constructors.<br>
34   *
35   * <code>
36   * final CSVParser parser =<br>
37   * new CSVParserBuilder()<br>
38   * .withSeparator('\t')<br>
39   * .withIgnoreQuotations(true)<br>
40   * .build();<br>
41   * final CSVReader reader =<br>
42   * new CSVReaderBuilder(new StringReader(csv))<br>
43   * .withSkipLines(1)<br>
44   * .withCSVParser(parser)<br>
45   * .build();<br>
46   * </code></p>
47   *
48   * @see com.opencsv.CSVReader
49   */
50  public class CSVReaderBuilder extends CSVReaderBaseBuilder<CSVReader> {
51  
52      /**
53       * Sets the reader to an underlying CSV source.
54       *
55       * @param reader The reader to an underlying CSV source.
56       */
57      public CSVReaderBuilder(
58              final Reader reader) {
59          super(reader);
60          if (reader == null) {
61              throw new IllegalArgumentException(ResourceBundle.getBundle(ICSVParser.DEFAULT_BUNDLE_NAME).getString("reader.null"));
62          }
63      }
64  
65      /**
66       * Sets the number of lines to skip before reading.
67       *
68       * @param skipLines The number of lines to skip before reading.
69       * @return {@code this}
70       */
71      public CSVReaderBuilder withSkipLines(
72              final int skipLines) {
73          this.skipLines = Math.max(skipLines, 0);
74          return this;
75      }
76  
77      /**
78       * Sets the parser to use to parse the input.
79       *
80       * @param icsvParser The parser to use to parse the input.
81       * @return {@code this}
82       */
83      public CSVReaderBuilder withCSVParser(
84              final ICSVParser icsvParser) {
85          this.icsvParser = icsvParser;
86          return this;
87      }
88  
89      /**
90       * Creates the {@link CSVReader}.
91       * @return The {@link CSVReader} based on the set criteria.
92       */
93      @Override
94      public CSVReader build() {
95          final ICSVParser parser = getOrCreateCsvParser();
96          return new CSVReader(reader, skipLines, parser, keepCR, verifyReader, multilineLimit, errorLocale,
97                  lineValidatorAggregator, rowValidatorAggregator, rowProcessor);
98      }
99  
100     /**
101      * Sets if the reader will keep or discard carriage returns.
102      *
103      * @param keepCR True to keep carriage returns, false to discard.
104      * @return {@code this}
105      */
106     public CSVReaderBuilder withKeepCarriageReturn(boolean keepCR) {
107         this.keepCR = keepCR;
108         return this;
109     }
110 
111     /**
112      * Checks to see if the {@link CSVReader} should verify the reader state before
113      * reads or not.
114      *
115      * <p>This should be set to false if you are using some form of asynchronous
116      * reader (like readers created by the java.nio.* classes).</p>
117      *
118      * <p>The default value is true.</p>
119      *
120      * @param verifyReader True if {@link CSVReader} should verify reader before each read, false otherwise.
121      * @return {@code this}
122      */
123     public CSVReaderBuilder withVerifyReader(boolean verifyReader) {
124         this.verifyReader = verifyReader;
125         return this;
126     }
127 
128     /**
129      * Checks to see if it should treat a field with two separators, two quotes, or both as a null field.
130      *
131      * @param indicator {@link CSVReaderNullFieldIndicator} set to what should be considered a null field.
132      * @return {@code this}
133      */
134     public CSVReaderBuilder withFieldAsNull(CSVReaderNullFieldIndicator indicator) {
135         this.nullFieldIndicator = indicator;
136         return this;
137     }
138 
139     /**
140      * Sets the maximum number of lines allowed in a multiline record.
141      * More than this number in one record results in an IOException.
142      *
143      * @param multilineLimit No more than this number of lines is allowed in a
144      *                       single input record. The default is {@link CSVReader#DEFAULT_MULTILINE_LIMIT}.
145      * @return {@code this}
146      */
147     public CSVReaderBuilder withMultilineLimit(int multilineLimit) {
148         this.multilineLimit = multilineLimit;
149         return this;
150     }
151 
152     /**
153      * Sets the locale for all error messages.
154      *
155      * @param errorLocale Locale for error messages
156      * @return {@code this}
157      * @since 4.0
158      */
159     public CSVReaderBuilder withErrorLocale(Locale errorLocale) {
160         this.errorLocale = ObjectUtils.defaultIfNull(errorLocale, Locale.getDefault());
161         return this;
162     }
163 
164     /**
165      * Adds a {@link LineValidator} to the {@link CSVReader}.
166      * Multiple {@link LineValidator}s can be added with multiple calls.
167      *
168      * @param lineValidator {@link LineValidator} to inject.
169      * @return {@code this}
170      * @since 5.0
171      */
172     public CSVReaderBuilder withLineValidator(LineValidator lineValidator) {
173         lineValidatorAggregator.addValidator(lineValidator);
174         return this;
175     }
176 
177     /**
178      * Adds a {@link RowValidator} to the {@link CSVReader}.
179      * Multiple {@link RowValidator}s can be added with multiple calls.
180      *
181      * @param rowValidator {@link RowValidator} to inject
182      * @return {@code this}
183      * @since 5.0
184      */
185     public CSVReaderBuilder withRowValidator(RowValidator rowValidator) {
186         rowValidatorAggregator.addValidator(rowValidator);
187         return this;
188     }
189 
190     /**
191      * Adds a {@link RowProcessor} to the {@link CSVReader}.
192      * Only a single {@link RowProcessor} can be added so multiple calls will overwrite
193      * the previously set {@link RowProcessor}.
194      *
195      * @param rowProcessor {@link RowProcessor} to inject
196      * @return {@code this}
197      * @since 5.0
198      */
199     public CSVReaderBuilder withRowProcessor(RowProcessor rowProcessor) {
200         this.rowProcessor = rowProcessor;
201         return this;
202     }
203 }