I want to stream the lines contained in files but MOVING each file to another folder once it has been processed.
The current process is like this:
Explanation:>
You can chain a close action to a stream, which will be executed automatically in case of flatMap
:
Stream.generate(localFileProvider::getNextFile).takeWhile(Objects::nonNull)
.flatMap(file -> {
try {
Path p = file.toPath();
return Files.lines(p, Charset.defaultCharset()).onClose(() -> {
try { // move path/x/y/z to path/x/y/z.moved
Files.move(p, p.resolveSibling(p.getFileName()+".moved"));
} catch(IOException ex) { throw new UncheckedIOException(ex); }
});
} catch(IOException ex) { throw new UncheckedIOException(ex); }
})
.forEach(System.out::println);
It’s important that the documentation of onClose states:
Close handlers are run when the close() method is called on the stream, and are executed in the order they were added.
So the moving close handler is executed after the already existing close handler that will close the file handle used for reading the lines.
I used Charset.defaultCharset()
to mimic the behavior of the nested constructors new InputStreamReader(new FileInputStream(file)))
of your question’s code, but generally, you should use a fixed charset, like the Files.lines
’s default UTF-8 whenever possible.