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