2 * Copyright (C) 2007-2012 Mathieu Baudier
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.util
;
18 import java
.io
.BufferedReader
;
19 import java
.io
.IOException
;
20 import java
.io
.InputStream
;
21 import java
.io
.InputStreamReader
;
22 import java
.util
.ArrayList
;
23 import java
.util
.Collections
;
24 import java
.util
.List
;
26 import org
.argeo
.ArgeoException
;
29 * Parses a CSV file interpreting the first line as a header. The
30 * {@link #parse(InputStream)} method and the setters are synchronized so that
31 * the object cannot be modified when parsing.
33 public abstract class CsvParser
{
34 private char separator
= ',';
35 private char quote
= '\"';
37 private Boolean noHeader
= false;
38 private Boolean strictLineAsLongAsHeader
= true;
41 * Actually process a parsed line. If
42 * {@link #setStrictLineAsLongAsHeader(Boolean)} is true (default) the
43 * header and the tokens are guaranteed to have the same size.
46 * the current line number, starts at 1 (the header, if header
47 * processing is enabled, the first line otherwise)
49 * the read-only header or null if {@link #setNoHeader(Boolean)}
50 * is true (default is false)
54 protected abstract void processLine(Integer lineNumber
,
55 List
<String
> header
, List
<String
> tokens
);
57 public synchronized void parse(InputStream in
) {
61 public synchronized void parse(InputStream in
, String encoding
) {
62 BufferedReader reader
= null;
63 Integer lineCount
= 0;
66 reader
= new BufferedReader(new InputStreamReader(in
));
68 reader
= new BufferedReader(new InputStreamReader(in
, encoding
));
69 List
<String
> header
= null;
71 String headerStr
= reader
.readLine();
72 if (headerStr
== null)// empty file
75 header
= new ArrayList
<String
>();
76 StringBuffer currStr
= new StringBuffer("");
77 Boolean wasInquote
= false;
78 while (parseLine(headerStr
, header
, currStr
, wasInquote
)) {
79 headerStr
= reader
.readLine();
80 if (headerStr
== null)
84 header
= Collections
.unmodifiableList(header
);
88 lines
: while ((line
= reader
.readLine()) != null) {
89 line
= preProcessLine(line
);
95 List
<String
> tokens
= new ArrayList
<String
>();
96 StringBuffer currStr
= new StringBuffer("");
97 Boolean wasInquote
= false;
98 sublines
: while (parseLine(line
, tokens
, currStr
, wasInquote
)) {
99 line
= reader
.readLine();
104 if (!noHeader
&& strictLineAsLongAsHeader
) {
105 int headerSize
= header
.size();
106 int tokenSize
= tokens
.size();
107 if (tokenSize
== 1 && line
.trim().equals(""))
108 continue lines
;// empty line
109 if (headerSize
!= tokenSize
) {
110 throw new ArgeoException("Token size " + tokenSize
111 + " is different from header size "
112 + headerSize
+ " at line " + lineCount
113 + ", line: " + line
+ ", header: " + header
114 + ", tokens: " + tokens
);
117 processLine(lineCount
, header
, tokens
);
119 } catch (ArgeoException e
) {
121 } catch (IOException e
) {
122 throw new ArgeoException("Cannot parse CSV file (line: "
123 + lineCount
+ ")", e
);
128 } catch (Exception e2
) {
135 * Called before each (logical) line is processed, giving a change to modify
136 * it (typically for cleaning dirty files). To be overridden, return the
137 * line unchanged by default. Skip the line if 'null' is returned.
139 protected String
preProcessLine(String line
) {
144 * Parses a line character by character for performance purpose
146 * @return whether to continue parsing this line
148 protected Boolean
parseLine(String str
, List
<String
> tokens
,
149 StringBuffer currStr
, Boolean wasInquote
) {
150 // List<String> tokens = new ArrayList<String>();
152 // System.out.println("#LINE: " + str);
155 currStr
.append('\n');
157 char[] arr
= str
.toCharArray();
158 boolean inQuote
= wasInquote
;
159 // StringBuffer currStr = new StringBuffer("");
160 for (int i
= 0; i
< arr
.length
; i
++) {
162 if (c
== separator
) {
164 tokens
.add(currStr
.toString());
165 // System.out.println("# TOKEN: " + currStr);
166 currStr
.delete(0, currStr
.length());
168 // we don't remove separator that are in a quoted substring
170 // .println("IN QUOTE, got a separator: [" + c + "]");
173 } else if (c
== quote
) {
174 if (inQuote
&& (i
+ 1) < arr
.length
&& arr
[i
+ 1] == quote
) {
175 // case of double quote
176 currStr
.append(quote
);
179 inQuote
= inQuote ?
false : true;
187 tokens
.add(currStr
.toString());
188 // System.out.println("# TOKEN: " + currStr);
191 // throw new ArgeoException("Missing quote at the end of the line "
192 // + str + " (parsed: " + tokens + ")");
200 public char getSeparator() {
204 public synchronized void setSeparator(char separator
) {
205 this.separator
= separator
;
208 public char getQuote() {
212 public synchronized void setQuote(char quote
) {
216 public Boolean
getNoHeader() {
220 public synchronized void setNoHeader(Boolean noHeader
) {
221 this.noHeader
= noHeader
;
224 public Boolean
getStrictLineAsLongAsHeader() {
225 return strictLineAsLongAsHeader
;
228 public synchronized void setStrictLineAsLongAsHeader(
229 Boolean strictLineAsLongAsHeader
) {
230 this.strictLineAsLongAsHeader
= strictLineAsLongAsHeader
;