1 /*
2 * Copyright 2007 Kasper B. Graversen
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 org.supercsv.io;
17
18 import java.io.IOException;
19 import java.io.LineNumberReader;
20 import java.io.Reader;
21 import java.util.List;
22
23 import org.supercsv.prefs.CsvPreference;
24
25 /**
26 * Defines the standard behaviour of a Tokenizer. Extend this class if you want the line-reading functionality of the
27 * default {@link Tokenizer}, but want to define your own implementation of {@link #readColumns(List)}.
28 *
29 * @author James Bassett
30 * @since 2.0.0
31 */
32 public abstract class AbstractTokenizer implements ITokenizer {
33
34 private final CsvPreference preferences;
35
36 private final LineNumberReader lnr;
37
38 /**
39 * Constructs a new <tt>AbstractTokenizer</tt>, which reads the CSV file, line by line.
40 *
41 * @param reader
42 * the reader
43 * @param preferences
44 * the CSV preferences
45 * @throws NullPointerException
46 * if reader or preferences is null
47 */
48 public AbstractTokenizer(final Reader reader, final CsvPreference preferences) {
49 if( reader == null ) {
50 throw new NullPointerException("reader should not be null");
51 }
52 if( preferences == null ) {
53 throw new NullPointerException("preferences should not be null");
54 }
55 this.preferences = preferences;
56 lnr = new LineNumberReader(reader);
57 }
58
59 /**
60 * Closes the underlying reader.
61 */
62 public void close() throws IOException {
63 lnr.close();
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 public int getLineNumber() {
70 return lnr.getLineNumber();
71 }
72
73 /**
74 * Reads a line of text. Whenever a line terminator is read the current line number is incremented.
75 *
76 * @return A String containing the contents of the line, not including any line termination characters, or
77 * <tt>null</tt> if the end of the stream has been reached
78 * @throws IOException
79 * If an I/O error occurs
80 */
81 protected String readLine() throws IOException {
82 return lnr.readLine();
83 }
84
85 /**
86 * Gets the CSV preferences.
87 *
88 * @return the preferences
89 */
90 protected CsvPreference getPreferences() {
91 return preferences;
92 }
93
94 }