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

标签 java io sonarlint

我已经定义了输出流,如下所示 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/

相关文章:

java - 如何编写接受多种类型的函数?

java - 有没有办法更改 Jslider 的图标?

c - 如何清除 C 中的输入缓冲区?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

intellij-idea - 如何从用于 IntelliJ IDEA 的 SonarLint 中的即时分析中排除 JS 文件?

java - SonarQube,finally block 中的跳转语句(squid :S1143)

c# - 如何阻止 SonarLint 抑制的警告不断重新出现在 VS 错误屏幕中

java - 使用 Apache poi 将数据写入 Word 文档?

java - servlet 内的 html 表单处理

c# - 向用户显示文件无法加载到程序 C# 的消息