gpt4 book ai didi

java - 资源已关闭但 sonarlint 仍显示资源未关闭

转载 作者:行者123 更新时间:2023-12-02 01:20:09 28 4
gpt4 key购买 nike

我已经定义了输出流,如下所示OutputStream os=new FileOutputStream(文件);

尝试关闭如下资源

if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}}

仍然 sonarlint 显示“使用 try-with-resources 或在“finally”子句中关闭此“FileOutputStream”。”

最佳答案

如果您在同一方法中执行操作,请将关闭放在涉及流的打开部分的 try 的 finally 语句中,这一点很重要。这确保了在发生故障(异常)时,如果需要,流始终关闭

错误的声纳代码:

OutputStream os=new FileOutputStream(file);

... // your code operations with os

// If something is going really bad here and ends in exception the
// stream will never be closed

if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

更好的代码:

OutputStream os = null;
try{
os = new FileOutputStream(file);

... // your code operations with os

} finally{
// The stream is allways closed at the end of the method execution
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳代码(Java 1.7 或更高版本的情况)

try (OutputStream  os = new FileOutputStream(file)){

... // your code operations with os

// The stream is allways closed at the end of the try block
}

关于java - 资源已关闭但 sonarlint 仍显示资源未关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853040/

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