我有下面的代碼:資源應該被關閉 - 聲納
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