gpt4 book ai didi

java - FindBugs 不关心 InputStreams

转载 作者:行者123 更新时间:2023-12-02 11:45:44 25 4
gpt4 key购买 nike

我的代码如下所示:

try {

FileInputStream is = new FileInputStream("blah.properties");
properties.load(is);

}catch(...){ }
finally { }

最终没有关闭InputStream。我听到过关于 Java 1.6 及以后版本不需要关闭诸如此 InputStream 之类的资源的不同论点,垃圾收集器应该能够处理它,并且还有其他人仍然坚持关闭资源。

a)上述理论有确凿的证据吗?

b) 为什么 FindBugs 没有检测到这一点,即使在项目设置中打开了“低置信度”模式。

最佳答案

I have heard varying arguments about Java 1.6 onward not requiring resources such as this InputStream to close, the Garbage collector should be able to take care of it

垃圾收集将关闭已打开的资源,但为什么要这样做呢?根据 Joshua BlochEffective Java 第三版:

关闭资源经常被客户端忽视,会带来可预见的可怕性能后果...在处理必须关闭的资源时,始终优先使用 try-with-resources 而不是 try-finally .

<小时/>

Why doesn't FindBugs detect this, even at "Low Confidence" mode being turned on in the project settings.

我使用您的代码在 Eclipse 中运行 Findbugs。它对我也不起作用,但 Eclipse 的错误日志中出现 FindBugs 异常:

!ENTRY edu.umd.cs.findbugs.plugin.eclipse 4 4 2018-01-21 01:17:25.303
!MESSAGE The following errors occurred during FindBugs analysis:
!SUBENTRY 1 edu.umd.cs.findbugs.plugin.eclipse 4 0 2018-01-21 01:17:25.303
!MESSAGE Error scanning com/HelloWorld9 for referenced classes
!STACK 0
java.lang.IllegalArgumentException at org.objectweb.asm.ClassReader.<init>(ClassReader.java:170)

你看到同样的事情了吗?另外,note this :

...it looks like FindBugs will never support Java 9. SpotBugs is the replacement.

所以我用 SpotBugs 插件替换了 FindBugs 插件,它正确地报告了 Method may fail to close stream :

spotBugsWorks

如果您只是用 SpotBugs 替换 FindBugs,一切都应该没问题。

关于java - FindBugs 不关心 InputStreams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48217836/

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