Stuart McCulloch | 3fdcd85 | 2011-10-17 10:31:43 +0000 | [diff] [blame] | 1 | package aQute.lib.collections; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.util.*; |
| 5 | |
| 6 | public class LineCollection implements Iterator<String>, Closeable { |
| 7 | final BufferedReader reader; |
| 8 | String next; |
| 9 | |
| 10 | public LineCollection(InputStream in) throws IOException { |
| 11 | this(new InputStreamReader(in, "UTF8")); |
| 12 | } |
| 13 | |
| 14 | public LineCollection(File in) throws IOException { |
| 15 | this(new FileReader(in)); |
| 16 | } |
| 17 | |
| 18 | public LineCollection(Reader reader) throws IOException { |
| 19 | this(new BufferedReader(reader)); |
| 20 | } |
| 21 | |
| 22 | public LineCollection(BufferedReader reader) throws IOException { |
| 23 | this.reader = reader; |
| 24 | next = reader.readLine(); |
| 25 | } |
| 26 | |
| 27 | public boolean hasNext() { |
| 28 | return next != null; |
| 29 | } |
| 30 | |
| 31 | public String next() { |
| 32 | if (next == null) |
| 33 | throw new IllegalStateException("Iterator has finished"); |
| 34 | try { |
| 35 | String result = next; |
| 36 | next = reader.readLine(); |
| 37 | if (next == null) |
| 38 | reader.close(); |
| 39 | return result; |
| 40 | } catch (Exception e) { |
| 41 | // ignore |
| 42 | return null; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | public void remove() { |
| 47 | if (next == null) |
| 48 | throw new UnsupportedOperationException("Cannot remove"); |
| 49 | } |
| 50 | |
| 51 | public void close() throws IOException { |
| 52 | reader.close(); |
| 53 | } |
| 54 | } |