我有下面的代码:资源应该被关闭 - 声纳
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;
}
问题是声纳仍然抱怨fileIn
没有被关闭,虽然它在finally块中的第一资源解决。
Sonar在这种情况下如何工作?以及如何解决资源应该关闭规则?
我不知道这是否会解决这个问题,声纳,但你并不需要'试穿catch'你'finally'子句中 - 根据https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html – nbokmans
只是检查'InputStream'对象是否为null并关闭它们,如果不够的话请添加exFinally.printStackTrace()在catch块中查看是否在关闭资源期间发生任何异常 – diufanman