It is not based on NIO, but I would look at the Guava CharStreams.readLines (InputSupplier, LineProcessor) method . He does what you want, I would say:
File file = ... Foo result = CharStreams.readLines(Files.newReaderSupplier(file, Charsets.UTF_8), new LineProcessor<Foo>() { public boolean processLine(String line) { // do stuff for this line return true; // or false if you want to stop processing here } public Foo getResult() { return result; // if you create some result when processing the lines } });
In this case, a callback is used to process each line in the file sequentially. It does not load the next line into memory until you process the current one. If you do not want to create any single result object when reading rows, you can simply use LineProcessor<Void> and have getResult() return null .
source share