Skip to content

Commit 7af334d

Browse files
committed
Allow a caller to close the parser before reading all records and free resources. The parser and lexer now implement java.io.Closeable.
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/csv/trunk@1508475 13f79535-47bb-0310-9956-ffa450edef68
1 parent ee7335a commit 7af334d

2 files changed

Lines changed: 24 additions & 4 deletions

File tree

src/main/java/org/apache/commons/csv/CSVParser.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import static org.apache.commons.csv.Token.Type.TOKEN;
2121

22+
import java.io.Closeable;
2223
import java.io.IOException;
2324
import java.io.Reader;
2425
import java.io.StringReader;
@@ -80,7 +81,7 @@
8081
*
8182
* @version $Id$
8283
*/
83-
public class CSVParser implements Iterable<CSVRecord> {
84+
public class CSVParser implements Iterable<CSVRecord>, Closeable {
8485

8586
private final Lexer lexer;
8687
private final Map<String, Integer> headerMap;
@@ -233,6 +234,15 @@ private void addRecordValue() {
233234
record.add(input.equalsIgnoreCase(nullString) ? null : input);
234235
}}
235236

237+
/**
238+
* Closes resources.
239+
*/
240+
public void close() throws IOException {
241+
if (lexer != null) {
242+
lexer.close();
243+
}
244+
}
245+
236246
/**
237247
* Parses the CSV input according to the given format and returns the content as an array of {@link CSVRecord}
238248
* entries.
@@ -326,4 +336,5 @@ public void remove() {
326336
}
327337
};
328338
}
339+
329340
}

src/main/java/org/apache/commons/csv/Lexer.java

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,15 @@
2525
import static org.apache.commons.csv.Constants.TAB;
2626
import static org.apache.commons.csv.Constants.UNDEFINED;
2727

28+
import java.io.Closeable;
2829
import java.io.IOException;
2930

3031
/**
3132
* Abstract lexer class; contains common utility routines shared by lexers
3233
*
3334
* @version $Id$
3435
*/
35-
abstract class Lexer {
36+
abstract class Lexer implements Closeable {
3637

3738
/**
3839
* Constant char to use for disabling comments, escapes and encapsulation. The value -2 is used because it
@@ -191,7 +192,15 @@ private boolean isMetaChar(final int c) {
191192
return c == delimiter ||
192193
c == escape ||
193194
c == quoteChar ||
194-
c == commmentStart
195-
;
195+
c == commmentStart;
196196
}
197+
198+
/**
199+
* Closes resources.
200+
*/
201+
public void close() throws IOException {
202+
if (in != null) {
203+
in.close();
204+
}
205+
}
197206
}

0 commit comments

Comments
 (0)