【发布时间】:2016-11-15 09:10:55
【问题描述】:
我有以下代码:
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 在这种情况下如何工作?以及如何解决资源应该关闭规则?
【问题讨论】:
-
我不知道它是否能解决声纳问题,但您不需要在
finally子句中使用try-catch- 只需检查InputStream对象是否为空并关闭根据docs.oracle.com/javase/tutorial/essential/exceptions/… -
请在catch块中添加exFinally.printStackTrace()查看关闭资源时是否有异常
标签: java optimization sonarqube inputstream findbugs