Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
HowToKB/src/kb/howtokb/utils/FileLines.java
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
81 lines (67 sloc)
1.52 KB
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
package kb.howtokb.utils; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.Iterator; | |
/** | |
* An iterator over a file, line by line (simulates calling bufferedReader.readLine()). | |
* @author ntandon | |
* | |
*/ | |
public class FileLines implements Iterable<String> { | |
private BufferedReader br; | |
public FileLines(String filePath) throws FileNotFoundException { | |
br = | |
new BufferedReader(new InputStreamReader(new FileInputStream( | |
new File(filePath)))); | |
} | |
public static int countLines(String filePath) throws FileNotFoundException { | |
int ctr = 0; | |
for (String l : new FileLines(filePath)) { | |
ctr++; | |
} | |
return ctr; | |
} | |
@Override | |
protected void finalize() throws Throwable { | |
super.finalize(); | |
if (br != null) | |
br.close(); | |
} | |
@Override | |
public Iterator<String> iterator() { | |
return new Iterator<String>() { | |
String line; | |
@Override | |
public boolean hasNext() { | |
try { | |
if (br == null || !br.ready()) | |
return false; | |
line = br.readLine(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
if (line == null) { | |
try { | |
br.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return line != null; | |
} | |
@Override | |
public String next() { | |
return line; | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException( | |
"Not yet implemented FileLines.remove()"); | |
} | |
}; | |
} | |
} |