【问题标题】:Java- How can you close `FileInputStream` in finally block if the same method returns that `FileInputStream`Java-如果相同的方法返回`FileInputStream`,你如何在finally块中关闭`FileInputStream`
【发布时间】:2016-09-28 10:13:07
【问题描述】:

Sonar 正在显示以下代码的错误,该错误属于拦截器类型。它抱怨我没有关闭FileInputStream,但我该怎么做呢? FileInputStream 是方法的返回类型,如果我在此处关闭,那么它从调用的地方将毫无用处。请让我知道 - 如果相同的方法返回 FileInputStream,我如何在 finally 块中关闭 FileInputStream

代码如下:

@Override
public InputStream getInputStream() throws MissingObjectException {

    try {
        InputStream is;
        if (smbFile != null) {
            is = new BufferedInputStream(new SmbFileInputStream(smbFile), 60000);
        } 
        else {
            is = new BufferedInputStream(new FileInputStream(getFilePath()));
        }
        return is;
    }
    catch (Exception e) {
            throw new MissingObjectException();
    }
}

【问题讨论】:

  • 以文本形式将代码粘贴到问题中,格式正确。
  • @Antoniossss 他这么说。他不想关闭它,他表示想知道 IDE 为什么会抱怨。

标签: java sonarqube fileinputstream autocloseable


【解决方案1】:

在同一个函数中不需要关闭输入。问题可能是您不应该在 try{} 块中声明 InputStream is 以及放置 return 语句。

【讨论】:

    【解决方案2】:

    将声明放在 try 块之前

     InputStream is= null;
    try {
        if (smbFile != null) {
            is = new BufferedInputStream(new SmbFileInputStream(smbFile), 60000);             } else {
            is = new BufferedInputStream(new FileInputStream(getFilePath()));
        }
        return is;
    }
    catch (Exception e) {
            throw new MissingObjectException();
    }finally{
      if(is !=null){
      is.close();
     }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多