public interface LineProcessor<T> {
/**
* This method will be called once for each line.
* @param line the line read from the input, without delimiter
* **@return true to continue processing, false to stop**
*
*/
boolean processLine(String line) throws IOException;
T getResult();
}
例如:可以通过Files和LineProcessor组合来按行读取文件并处理。
private static Map<String, Integer> analyzeJavaFile(File codeFile) throws IOException {
return Files.readLines(codeFile, Charsets.UTF_8, new LineProcessor<Map<String, Integer>>() {
private Map<String, Integer> countMap = Maps.newHashMap();
@Override
public boolean processLine(String line) throws IOException {
//代码逻辑
return true;
//返回false则说明读取文件结束。
}
@Override
public Map<String, Integer> getResult() {
return this.countMap;
}
});
}