Skip to main content
 首页 » 编程设计

java中如何使用 IO 资源从源装饰 Stream 实例

2025年12月25日47pengyingh

如您所知,从 IO 资源生成的 Stream 需要显式关闭。

我想要一个类来装饰传递的 Stream,但不幸的是,鉴于过滤器操作是中间的,它们只是创建一个新实例,所以我失去了对关闭的控制

Stream<T> removeNulls(Stream<T> input){ 
    input.filter(Objects::nonNull) //At this point, the returned pointer is a whole different stream which does not bind closing to the old one 
} 

如果有一种方法可以将过滤器流的关闭绑定(bind)到原始流...那么这就是可能的

try (Stream<T> myDecoratedStream = MyClass.removeNulls(myRepo.streamAll())){ 
   myDecoratedStrean.... 
} 

请您参考如下方法:

似乎 onClose 就是您所追求的,例如:

yourStream.filter(....).onClose(SomeRunnable)