public class Test {
@org.junit.Test
public void lineProcessTest() throws IOException {
File file = new File(Test.class.getResource("/a.txt").getFile());
ArrayList<String> list = (ArrayList<String>) Files.readLines(file,Charsets.UTF_8,new LineProcessor<Object>() {
ArrayList<String> list = Lists.newArrayList();
@Override
public boolean processLine(String line) throws IOException {
if (line.contains("haha")) {
} else {
list.add(line);
}
return true;
}
@Override
public Object getResult() {
return list;
}
});
for (String s : list) {
System.out.println(s);
}
}
}
LineProcessor类中processLine的返回值为true时,继续处理下一行,否则停止处理:
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;
/** Return the result of processing all the lines. */
T getResult();
}