Skip to content

Instantly share code, notes, and snippets.

@olim7t
Created June 4, 2012 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olim7t/2866946 to your computer and use it in GitHub Desktop.
Save olim7t/2866946 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/** Streams the lines of a {@link BufferedReader} while applying some parsing method. */
abstract class LineParsingIterator<T> implements Iterator<T> {
private final BufferedReader input;
private T buffered; // parsed but not yet returned to the client
private int lineNumber;
public LineParsingIterator(BufferedReader input) {
this.input = input;
}
/** @return {@code null} to discard the current line (e.g. comments) */
protected abstract T parse(String line, int lineNumber);
@Override
public boolean hasNext() {
if (buffered == null) buffered = findAndParseNext();
return (buffered != null);
}
@Override
public T next() {
if (buffered == null) buffered = findAndParseNext();
if (buffered == null) throw new NoSuchElementException();
T result = buffered;
buffered = null;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private T findAndParseNext() {
while (true) {
String line = readLine();
if (line == null) return null; // EOF
T result = parse(line, lineNumber);
if (result == null) continue;
return result;
}
}
private String readLine() {
try {
String line = input.readLine();
if (line != null) lineNumber += 1;
return line;
} catch (IOException e) {
throw new ParsingException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment