流式传输文件并在读取后移动它们 [英] Streaming files and moving them after read

查看:107
本文介绍了流式传输文件并在读取后移动它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想流式传输文件中包含的行,但是在处理完每个文件后将其移动到另一个文件夹中.

当前过程如下:

说明:

  1. 我创建了一个StreamFile s
  2. 我为每个人创建一个BufferedReader
  3. flatMapBufferedReader
  4. Stream
  5. 我打印每一行.

代码(为简化起见,省略了例外):

(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;

是否可以在完全读取每个文件后将其移动并继续处理流中的其他文件?

解决方案

您可以

onClose 的文档指出:

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆