saz
saz

Reputation: 291

SONAR issue - Close this FileInputStream

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

Upvotes: 1

Views: 2231

Answers (2)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

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.

Upvotes: 2

Amila
Amila

Reputation: 5213

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)

Upvotes: 1

Related Questions