Created
June 4, 2012 07:27
-
-
Save olim7t/2866946 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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