0
点赞
收藏
分享

微信扫一扫

sonar代码扫描bug:Use try-with-resources or close this "FileInputStream" in a "finally" clause.

sonar代码扫描bug:Use try-with-resources or close this "FileInputStream" in a "finally" clause._sonar

 

 

下面代码

/**
* 读取文件到byte数组
*
* @param tradeFile
* @return
*/
public static byte[] file2byte(File tradeFile) {
try {
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
byte[] buffer = bos.toByteArray();
return buffer;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

上面代码虽然调用了流的close方法,但可能会因中间程序异常致使文件流未关闭。如果应用程序运行过程中这个方法频繁被访问,就有可能导致频繁GC,甚至OOM错误。

SonarQube在扫描到这段代码时,会提示关闭文件流:Use try-with-resources or close this "FileInputStream" in a "finally" clause.

sonar代码扫描bug:Use try-with-resources or close this "FileInputStream" in a "finally" clause._sonar_02

我们用try-with-resources语法糖的方式来改进这段代码,try-with-resouces相当于显式在finally块里调用close方法(从build后的.class文件可以看出来)。为了保证资源及时关闭,我们往往要在finally里写一堆代码,使用这个java语法糖可以让我们专注应用开发,无需关注资源释放问题(参考:​​深入理解 Java try-with-resource 语法糖​​)。如下:

 

public static byte[] file2byte(File tradeFile) {
try (FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream()){
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
byte[] buffer = bos.toByteArray();
return buffer;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

 

当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--​​buguge​​



举报

相关推荐

0 条评论