01: package org.jical;
02:
03: import java.io.IOException;
04: import java.io.InputStream;
05: import java.io.InputStreamReader;
06: import java.io.BufferedReader;
07: import java.io.Reader;
08: import java.io.UnsupportedEncodingException;
09: import java.util.Iterator;
10: import java.util.List;
11: import java.util.ArrayList;
12:
13: public class LineIterator implements Iterator {
14:
15: private BufferedReader m_reader;
16: private List m_lines = new ArrayList();
17:
18: public LineIterator(InputStream stream) {
19: this (new InputStreamReader(stream));
20: }
21:
22: public LineIterator(InputStream stream, String enc)
23: throws UnsupportedEncodingException {
24: this (new InputStreamReader(stream, enc));
25: }
26:
27: public LineIterator(Reader reader) {
28: if (reader instanceof BufferedReader) {
29: m_reader = (BufferedReader) reader;
30: } else {
31: m_reader = new BufferedReader(reader);
32: }
33: }
34:
35: public boolean hasNext() {
36: checkLines();
37: return (!m_lines.isEmpty());
38: }
39:
40: public Object next() {
41: if (hasNext()) {
42: return m_lines.remove(0);
43: }
44: return null;
45: }
46:
47: public void remove() throws UnsupportedOperationException {
48: throw new UnsupportedOperationException();
49: }
50:
51: private void checkLines() {
52: synchronized (m_lines) {
53: if ((m_lines.size()) < 1 && (m_reader != null)) {
54: try {
55: String line = m_reader.readLine();
56: if (line != null) {
57: m_lines.add(new StringBuffer(line));
58: checkLines();
59: } else {
60: m_reader.close();
61: m_reader = null;
62: }
63: } catch (IOException ex) {
64: ex.printStackTrace();
65: }
66: }
67: }
68: }
69: }
|