资源应该关闭 - 声纳

时间:2016-11-15 09:10:56

标签: java optimization sonarqube inputstream findbugs

我有以下代码:

public static byte[] readSomeFile(String filePath) {
 byte[] buffer = new byte[FILE_SIZE];
 FileInputStream fileIn = null;
 BufferedInputStream buffIn = null;
 DataInputStream inData = null;

 int size = 0;
 byte[] someArray= null;
 try {
  fileIn = new FileInputStream(filePath);
  buffIn = new BufferedInputStream(fileIn);
  inData = new DataInputStream(buffIn);
  size = inData.read(buffer, 0, FILE_SIZE);
  someArray= new byte[size];
  System.arraycopy(buffer, 0, someArray, 0, size);
 } catch (IOException e) {
  //log(Log.ERROR,"IO ERROR: " + e.toString());
 } finally {
  try {
   if (null != fileIn) {
    fileIn.close();
   }
   if (null != buffIn) {
    buffIn.close();
   }
   if (null != inData) {
    inData.close();
   }
  } catch (Exception exFinally) {
   // some stuff
   someArray= null;
  }
 }
 return someArray;
}

问题是Sonar仍抱怨fileIn未被关​​闭,尽管它是finally块中解决的第一个资源。

Sonar如何在这种情况下工作?以及如何解决 资源应该关闭 规则?

1 个答案:

答案 0 :(得分:1)

如果您必须使用Java 7及以上版本,我建议您使用try with resources新功能中引入的Java 7

Try-with-resources中的{p> Java 7是一种新的exception处理机制,可以更轻松地正确关闭try-catch block.

中使用的资源

关于你的代码:

finally {
  try {
   if (null != fileIn) {
    fileIn.close();
   }
   if (null != buffIn) {
    buffIn.close();
   }
   if (null != inData) {
    inData.close();
   }
  } catch (Exception exFinally) {
   // some stuff
   someArray= null;
  }
 }

您是否注意到丑陋的双重尝试?

但是,如果您使用了try with resources,则系统会自动调用close(),如果throwsException相同,则会被强制调用(as specified in the Java Language Specification 14.20.3)。你的情况也是如此。我希望它有所帮助。

因此,您的代码将如下所示:

public static byte[] readSomeFile(String filePath) {
         byte[] buffer = new byte[FILE_SIZE];
         int size = 0;
         byte[] someArray= null;
         try (FileInputStream fileIn = new FileInputStream(filePath);
                 BufferedInputStream buffIn = new BufferedInputStream(fileIn);
                 DataInputStream inData = new DataInputStream(buffIn);) {

          size = inData.read(buffer, 0, FILE_SIZE);
          someArray= new byte[size];
          System.arraycopy(buffer, 0, someArray, 0, size);
         } catch (IOException e) {
          //log(Log.ERROR,"IO ERROR: " + e.toString());
         } 
         return someArray;
    }