Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LineReader
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;
public class LineReader implements Iterator<String>, Iterable<String> {
BufferedReader reader;
String next = null;
public LineReader(String fileName) throws Exception {
InputStream in = new FileInputStream(fileName);
if (fileName.endsWith(".gz")) {
in = new GZIPInputStream(in);
}
reader = new BufferedReader(new InputStreamReader(in));
}
public LineReader(InputStream in) throws Exception {
this.reader = new BufferedReader(new InputStreamReader(in));
}
@Override
public boolean hasNext() {
try {
next = reader.readLine();
if (next == null) {
reader.close();
return false;
}
return true;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String next() {
return next;
}
@Override
public void remove() {
}
@Override
public Iterator<String> iterator() {
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment