【问题标题】:Files.newDirectoryStream throws java.lang.IllegalStateException: Iterator already obtained [duplicate]Files.newDirectoryStream 抛出 java.lang.IllegalStateException:已获得迭代器 [重复]
【发布时间】:2020-04-18 15:03:23
【问题描述】:

下面的代码是遍历文件夹中的文件列表,以便在db中创建数据,但是抛出IllegalStateException:Iterator已经获得异常。

Flux.fromIterable(Files.newDirectoryStream(Paths.get(VIDEO_FILE_LOCATION)))
          .map(file -> new VideoFile(file.getFileName()
                                         .toString()))
          .subscribe(f -> videoRepository.save(f));

全栈

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:787) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:768) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE]
    at com.kalarikkal.KalarikkalApplication.main(Kalarikkalpplication.java:30) ~[main/:na]
Caused by: reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalStateException: Iterator already obtained
Caused by: java.lang.IllegalStateException: Iterator already obtained

无法更正此问题。请帮忙。

【问题讨论】:

  • 请发布完整的堆栈跟踪
  • 你能确定你只在这个粘贴的代码中使用Files.newDirectoryStream(Paths.get(VIDEO_FILE_LOCATION)吗?像这个流可以迭代一次。如果你需要再次迭代它,那么你必须再次写Files.newDirectoryStream(Paths.get(VIDEO_FILE_LOCATION)这个。
  • 是的,我在 CommandLineRunner 中使用它来填充数据库中的文件名,没有其他地方。在搜索中,我也遇到了关于 DirectoryStream 仅迭代一次的答案。但是在这里,只有一次迭代对吗?
  • 对不起兄弟,我无法从头到尾重现问题。甚至我也尝试在 commanlinerunner 中实现它。但从我这边开始一切都很顺利。
  • 你的意思是类似的代码在你最后工作?! .也许有一天我会找出原因!感谢您的帮助。

标签: spring-boot spring-webflux


【解决方案1】:

根据 123 的建议,我将代码更改如下。它工作..

    @Bean
      CommandLineRunner init(MongoOperations mongoOperations)
      {
        return args ->
        {
          mongoOperations.dropCollection(VideoFile.class);
    Path myDir = Paths.get(VIDEO_FILE_LOCATION);
          Stream<Path> directorStream = Files.list(myDir);
          Flux.fromStream(directorStream)
              .doOnNext(path -> mongoOperations.insert(new VideoFile(path.getFileName()
                                                                         .toString())))
              .subscribe();
        };
    }

【讨论】:

  • 我在 CommandLineRunner 中使用这个块来获取文件名并反应性地插入 Mongo。我已经更改了上面的代码,现在正在使用 MongoOperations。 mongoOperations.insert(new VideoFile(path.getFileName() .toString()));
  • 我在你的第一个代码中遇到了和你一样的错误。经过一段时间的搜索,没有找到任何解决方案。我像你一样更改了我的代码,它有效。
猜你喜欢
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
相关资源
最近更新 更多