设为首页 加入收藏

TOP

sonar代码扫描bug:Use try-with-resources or close this "FileInputStream" in a "finally" clause.
2023-07-25 21:40:17 】 浏览:44
Tags:sonar bug:Use try-with-resources close this " FileInputStream" 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;
}

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇面试官:从 MySQL 读取 100w 数据.. 下一篇docker实战

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目