gpt4 book ai didi

java - Supplier 应该用来提供文件流吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:09:54 25 4
gpt4 key购买 nike

我需要多次提供文件的 Stream 以便可以在不同时间对其执行不同的操作,我使用了以下供应商:

Supplier<Stream<String>> linesSupplier = () -> {
try
{
return Files.lines(Paths.get(file.toURI()));
}
catch (IOException e)
{
log.error("Error while supplying file " + file.getName(), e);
}
return null;
};

不幸的是,它会导致 file handle leak ,所以我尝试按照建议使用 try-with-resource。

Supplier<Stream<String>> linesSupplier = () -> {
try(Stream<String> lines = Files.lines(Paths.get(file.toURI())))
{
return lines;
}
catch (IOException e)
{
log.error("Error while supplying file " + file.getName(), e);
}
return null;
};

但现在我第一次使用 linesSupplier.get() 时,我得到一个 java.lang.IllegalStateException .

这是否表明我应该在任何情况下都积极避免 Supplier

最佳答案

当然不是 - 你应该使用 Supplier当你需要的时候。这里的问题是 Stream类(class)工具AutoCloseable和你的 try-with-resource称它为 close结束后的方法。

因此,要么将 Supplier负责关闭 Stream通过移动 try-with-resource或者可以将其他东西作为 Stream 返回,例如 List<String> .

关于java - Supplier 应该用来提供文件流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47304161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com