Created
June 19, 2012 06:52
-
-
Save aniljava/2952678 to your computer and use it in GitHub Desktop.
LineReader
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.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