buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

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;
}

 

posted on 2023-03-02 14:00  buguge  阅读(630)  评论(0编辑  收藏  举报