欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

sonar代码扫描bug:Use try-with-resources or close this "FileInputStream" in a "finally" clause.,如果应用程序运行过程

来源: javaer 分享于  点击 8212 次 点评:57

sonar代码扫描bug:Use try-with-resources or close this "FileInputStream" in a "finally" clause.,如果应用程序运行过程


 

 

下面代码

/**
 * 读取文件到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.

我们用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
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/p/17171588.html


相关文章

    暂无相关文章
相关栏目:

用户点评