import java.util.Iterator; import java.util.NoSuchElementException; import java.io.BufferedReader; import java.io.IOException; public class LineIterator implements Iterator { public static final Iterable lines(final BufferedReader in) { return new Iterable() { private BufferedReader in_ = in; public Iterator iterator() { if (in_ == null) throw new IllegalStateException("iterator cannot be called more than once"); Iterator it = new LineIterator(in_); in_ = null; return it; } }; } private final BufferedReader in; private String next; public LineIterator(BufferedReader in) { this.in = in; advance(); } private void advance() { try { next = in.readLine(); } catch (IOException e) { next = null; } } public String next() { if (!hasNext()) throw new NoSuchElementException(); String next = this.next; advance(); return next; } public boolean hasNext() { return next != null; } public void remove() { throw new UnsupportedOperationException(); } }