流式传输文件并在读取后移动它们 [英] Streaming files and moving them after read
问题描述
我想流式传输文件中包含的行,但是在处理完每个文件后将其移动到另一个文件夹中.
当前过程如下:
说明:
- 我创建了一个
Stream
个File
s - 我为每个人创建一个
BufferedReader
- 我
flatMap
到BufferedReader
的 - 我打印每一行.
Stream
行
代码(为简化起见,省略了例外):
(1) Stream.generate(localFileProvider::getNextFile)
(2) .map(file -> new BufferedReader(new InputStreamReader(new FileInputStream(file))))
(3) .flatMap(BufferedReader::lines)
(4) .map(System.out::println)
.MOVE_EACH_FILE_FROM_INPUT_FOLDER_TO_SOME_OTHER_FOLDER;
是否可以在完全读取每个文件后将其移动并继续处理流中的其他文件?
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.
这篇关于流式传输文件并在读取后移动它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!