2 * Copyright (C) 2007-2012 Argeo GmbH
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
;
27 * Parses a CSV file interpreting the first line as a header. The
28 * {@link #parse(InputStream)} method and the setters are synchronized so that
29 * the object cannot be modified when parsing.
31 public abstract class CsvParser
{
32 private char separator
= ',';
33 private char quote
= '\"';
35 private Boolean noHeader
= false;
36 private Boolean strictLineAsLongAsHeader
= true;
39 * Actually process a parsed line. If
40 * {@link #setStrictLineAsLongAsHeader(Boolean)} is true (default) the
41 * header and the tokens are guaranteed to have the same size.
44 * the current line number, starts at 1 (the header, if header
45 * processing is enabled, the first line otherwise)
47 * the read-only header or null if {@link #setNoHeader(Boolean)}
48 * is true (default is false)
52 protected abstract void processLine(Integer lineNumber
,
53 List
<String
> header
, List
<String
> tokens
);
56 * Parses the CSV file (stream is closed at the end)
58 public synchronized void parse(InputStream in
) {
63 * Parses the CSV file (stream is closed at the end)
65 public synchronized void parse(InputStream in
, String encoding
) {
66 BufferedReader reader
= null;
67 Integer lineCount
= 0;
70 reader
= new BufferedReader(new InputStreamReader(in
));
72 reader
= new BufferedReader(new InputStreamReader(in
, encoding
));
73 List
<String
> header
= null;
75 String headerStr
= reader
.readLine();
76 if (headerStr
== null)// empty file
79 header
= new ArrayList
<String
>();
80 StringBuffer currStr
= new StringBuffer("");
81 Boolean wasInquote
= false;
82 while (parseLine(headerStr
, header
, currStr
, wasInquote
)) {
83 headerStr
= reader
.readLine();
84 if (headerStr
== null)
88 header
= Collections
.unmodifiableList(header
);
92 lines
: while ((line
= reader
.readLine()) != null) {
93 line
= preProcessLine(line
);
99 List
<String
> tokens
= new ArrayList
<String
>();
100 StringBuffer currStr
= new StringBuffer("");
101 Boolean wasInquote
= false;
102 sublines
: while (parseLine(line
, tokens
, currStr
, wasInquote
)) {
103 line
= reader
.readLine();
108 if (!noHeader
&& strictLineAsLongAsHeader
) {
109 int headerSize
= header
.size();
110 int tokenSize
= tokens
.size();
111 if (tokenSize
== 1 && line
.trim().equals(""))
112 continue lines
;// empty line
113 if (headerSize
!= tokenSize
) {
114 throw new UtilsException("Token size " + tokenSize
115 + " is different from header size "
116 + headerSize
+ " at line " + lineCount
117 + ", line: " + line
+ ", header: " + header
118 + ", tokens: " + tokens
);
121 processLine(lineCount
, header
, tokens
);
123 } catch (UtilsException e
) {
125 } catch (IOException e
) {
126 throw new UtilsException("Cannot parse CSV file (line: "
127 + lineCount
+ ")", e
);
129 StreamUtils
.closeQuietly(reader
);
134 * Called before each (logical) line is processed, giving a change to modify
135 * it (typically for cleaning dirty files). To be overridden, return the
136 * line unchanged by default. Skip the line if 'null' is returned.
138 protected String
preProcessLine(String line
) {
143 * Parses a line character by character for performance purpose
145 * @return whether to continue parsing this line
147 protected Boolean
parseLine(String str
, List
<String
> tokens
,
148 StringBuffer currStr
, Boolean wasInquote
) {
149 // List<String> tokens = new ArrayList<String>();
151 // System.out.println("#LINE: " + str);
154 currStr
.append('\n');
156 char[] arr
= str
.toCharArray();
157 boolean inQuote
= wasInquote
;
158 // StringBuffer currStr = new StringBuffer("");
159 for (int i
= 0; i
< arr
.length
; i
++) {
161 if (c
== separator
) {
163 tokens
.add(currStr
.toString());
164 // System.out.println("# TOKEN: " + currStr);
165 currStr
.delete(0, currStr
.length());
167 // we don't remove separator that are in a quoted substring
169 // .println("IN QUOTE, got a separator: [" + c + "]");
172 } else if (c
== quote
) {
173 if (inQuote
&& (i
+ 1) < arr
.length
&& arr
[i
+ 1] == quote
) {
174 // case of double quote
175 currStr
.append(quote
);
178 inQuote
= inQuote ?
false : true;
186 tokens
.add(currStr
.toString());
187 // System.out.println("# TOKEN: " + currStr);
190 // throw new ArgeoException("Missing quote at the end of the line "
191 // + str + " (parsed: " + tokens + ")");
199 public char getSeparator() {
203 public synchronized void setSeparator(char separator
) {
204 this.separator
= separator
;
207 public char getQuote() {
211 public synchronized void setQuote(char quote
) {
215 public Boolean
getNoHeader() {
219 public synchronized void setNoHeader(Boolean noHeader
) {
220 this.noHeader
= noHeader
;
223 public Boolean
getStrictLineAsLongAsHeader() {
224 return strictLineAsLongAsHeader
;
227 public synchronized void setStrictLineAsLongAsHeader(
228 Boolean strictLineAsLongAsHeader
) {
229 this.strictLineAsLongAsHeader
= strictLineAsLongAsHeader
;