【问题标题】:I have a bug "Method may fail to clean up stream or resource" in findBugs and I don't know how to solve this bug, so can someone solve it please?我在 findBugs 中有一个错误“方法可能无法清理流或资源”,我不知道如何解决这个错误,请问有人可以解决吗?
【发布时间】:2021-07-15 04:55:52
【问题描述】:

此方法可能无法清理(关闭、处置)流、数据库对象或其他需要显式清理操作的资源。 一般来说,如果一个方法打开一个流或其他资源,该方法应该使用 try/finally 块来确保在方法返回之前清理流或资源。

这是代码:

public void setSource(File file) throws IOException {

 m_structure = null;
 setRetrieval(NONE);

 if (file == null) {
  throw new IOException("Source file object is null!");
 }

 try {
  setSource(new FileInputStream(file));
 } 
 catch (FileNotFoundException ex) {
  throw new IOException("File not found");
 }
 
 m_File = file.getAbsolutePath();
}

【问题讨论】:

    标签: findbugs spotbugs


    【解决方案1】:

    由于以下行,您会收到错误:

    new FileInputStream(file)

    理论上,您可以关闭 setSource(InputStream is) 方法内的输入流,但这不是正确的范围。惯例是关闭您打开它的流。因此,如果您将代码更改为以下内容,它应该会删除警告。请注意,您的 catch 块没有意义,因为 FileNotFoundException 已经是 IOException。有两种可能:

    1. 尝试资源:

      public void setSource(File file) throws YourOwnApplicationException{
      
       if (file == null) {
        throw new YourOwnApplicationException("Source file object is null!");
       }
      
       try (FileInputStream fis=new FileInputStream(file)){
        setSource(fis);
       } 
       catch (IOException | FileNotFoundException ex) {
        throw new YourOwnApplicationException("File not found");
       }
      }
      
    2. Java 7/8 之前的方式:

      public void setSource(File file) throws YourOwnApplicationException {
      
       if (file == null) {
        throw new YourOwnApplicationException ("Source file object is null!");
       }
      
       FileInputStream fis=null;
       try {
           fis = new FileInputStream(file);
           setSource(fis);
       } 
       catch (IOException | FileNotFoundException ex) {
        throw new YourOwnApplicationException("File not found");
       }
       finally {
           if(fis!=null) {
               try {
                   fis.close();
               }
               catch(IOException ioe) {
                   //swallow
               }
           }
       }
      }
      

    如果你这样做,也意味着你必须在setSource(InputStream is) 方法中使用你的InputStream。否则关闭它就没有意义...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多