资源应该关闭 - 声纳

Resources should be closed - Sonar

我有如下一段代码:

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 在这种情况下如何工作?以及如何解决 应关闭资源 规则?

如果您必须使用 Java 7 及更高版本,我更喜欢您使用 Java 7 新功能中引入的 try with resources

Java 7 中的

Try-with-resources 是一种新的 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 resourcesclose() 会被自动调用,如果它 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;
    }