SONAR issue - Close this FileInputStream

2019-07-22 05:24发布

How do I fix this SONAR issue? Close this FileInputStream.

Thanks in advance!

File billFile = new File(filePath);
try (BufferedReader br = new BufferedReader(new InputStreamReader(
        new FileInputStream(billFile), DEFAULTCHARSET));) { 

    ... 
    br.close();
} catch (FileNotFoundException e) {
    LOG.error(e.getMessage());              
} catch (IOException e) {
    LOG.error(e.getMessage(), e);               
}

2条回答
男人必须洒脱
2楼-- · 2019-07-22 06:01

As you use the try-with-resources statement, you don't need to close your BufferedReader explicitly anymore so simply remove br.close(); from your current code which should be enough to fix your sonar issue as a BufferedReader will close the underlying InputStreamReader on close and the InputStreamReader will close your FileInputStream on close.


If not enough, you could simply rewrite your code to explicitly declare your FileInputStream as a resource of your try-with-resources statement like below:

try (FileInputStream fis = new FileInputStream(billFile);
     Reader reader = new InputStreamReader(fis, DEFAULTCHARSET);
     BufferedReader br = new BufferedReader(reader) {
     ...

If it still doesn't work make sure that sonar is properly configured for Java 7 and above otherwise it won't be aware of the try-with-resources statement which would lead to this violation raise.

查看更多
孤傲高冷的网名
3楼-- · 2019-07-22 06:01

It might be the case that you're using an outdated SONAR version or rule-set. Check the version. (try-with-resources was introduced with Java 7)

查看更多
登录 后发表回答