1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.platform.camel.core.process.splitter.support;
17
18 import org.apache.camel.util.ObjectHelper;
19 import org.openehealth.ipf.platform.camel.core.process.splitter.Splitter;
20
21 import java.io.BufferedReader;
22 import java.io.FileReader;
23 import java.io.IOException;
24 import java.util.Iterator;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public class TextFileIterator implements Iterator<String> {
48 private static final LineSplitterLogic DEFAULT_LINE_SPLITTER_LOGIC =
49 new NoopLineSplitterLogic();
50
51 private BufferedReader reader;
52 private String[] nextSplitLine;
53 private int curSplitLineIdx;
54 private final LineSplitterLogic lineSplitterLogic;
55 private boolean closed;
56
57
58
59
60
61
62
63
64 public TextFileIterator(String filename) throws IOException {
65
66 ObjectHelper.notNull(filename, "filename");
67
68 lineSplitterLogic = DEFAULT_LINE_SPLITTER_LOGIC;
69
70 try {
71 reader = new BufferedReader(new FileReader(filename));
72 readNextLine();
73 }
74 catch (IOException e) {
75 close();
76 throw e;
77 }
78 }
79
80
81
82
83
84
85
86
87
88
89 public TextFileIterator(String filename, LineSplitterLogic lineSplitterLogic)
90 throws IOException {
91
92 ObjectHelper.notNull(filename, "filename");
93 ObjectHelper.notNull(lineSplitterLogic, "lineSplitterLogic");
94
95 this.lineSplitterLogic = lineSplitterLogic;
96 reader = new BufferedReader(new FileReader(filename));
97
98 readNextLine();
99 }
100
101
102
103
104 @Override
105 public boolean hasNext() {
106 return nextSplitLine != null;
107 }
108
109
110
111
112 @Override
113 public String next() {
114 String curLine = nextSplitLine[curSplitLineIdx];
115 advance();
116 return curLine;
117 }
118
119
120
121
122
123 @Override
124 public void remove() {
125 close();
126 throw new UnsupportedOperationException();
127 }
128
129
130
131 public boolean isClosed() {
132 return closed;
133 }
134
135
136
137
138 public void close() {
139 closed = true;
140 if (reader != null) {
141 try {
142 reader.close();
143 } catch (IOException e) {
144
145
146 }
147 }
148 }
149
150
151 private void advance() {
152 try {
153 if (hasNext()) {
154 if (curSplitLineIdx < nextSplitLine.length - 1) {
155 ++curSplitLineIdx;
156 }
157 else {
158 readNextLine();
159 }
160 }
161 } catch (IOException e) {
162 close();
163 throw new IllegalStateException(e);
164 }
165 }
166
167 private void readNextLine() throws IOException {
168 String nextLine = reader.readLine();
169 if (nextLine != null) {
170 nextSplitLine = lineSplitterLogic.splitLine(nextLine);
171 curSplitLineIdx = 0;
172 }
173 else {
174 nextSplitLine = null;
175 close();
176 }
177 }
178 }
179