【问题标题】:Java stream: Generate objects directly from an input file and save the objects with Spring DataJava 流:直接从输入文件生成对象并使用 Spring Data 保存对象
【发布时间】:2018-01-11 14:23:03
【问题描述】:

我将从输入文件的每一行生成一个 Foo 对象,并在下一步中将所有对象保存在数据库中 (Spring Data JPA)。

    //read file into stream
    try (Stream<String> stream = Files.lines((path), Charset.forName("ISO-8859-1"))) {

        Stream<Foo> rStream = stream.map(line -> new Foo(line));           
        rStream.forEach(line -> fooRepository.save(line));

    } catch (IOException e) {
        e.printStackTrace();
    }

我收到了Unhandled exception: java.lang.Exception,因为 Foo 类的构造函数可以传播来自 MyParser 类的异常:

public Foo(String row) throws Exception {
        String split[] = StringUtils.split(row, "Ú");
        field    =   MyParser.getInt(split[0]);
}

是否仍然可以使用 Java 流 API?也许只有一个很棒的流?像这样的东西:

stream.map(Foo::new).forEach(foo -> fooRepository.save(foo));

我使用 Java 8 和 Spring Boot 1.5.8。

【问题讨论】:

  • throws Exception?为您提供正确的创建 API 的权利,该 API 对于所有意图和目的都是不可用的。您希望人们如何处理 new Foo 可以抛出absolutely any Exception 的信息? API 的使用者应该如何处理这个非常有用的花絮?
  • @BoristheSpider amazing useful tidbit :) 加一!
  • 另外,这应该是stream.map(Foo::new).forEach(fooRepository::save)

标签: spring java-8 stream spring-data


【解决方案1】:

如果您可以编辑课程,为什么不直接抛出RuntimeException 而不是抛出Exception。如果您使用的 API 仍然抛出 Exception,您可以将其包装成:

catch(Exception e){
    throw new RuntimeException(e);
}

那么你可以将其简化为:

 stream.map(Foo::new).forEach(fooRepository::save)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2014-08-15
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多