Reputation: 81
I have defined Output stream like below
OutputStream os=new FileOutputStream(file);
Tried to close the resource like below
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}}
Still sonarlint showing "Use try-with-resources or close this "FileOutputStream" in a "finally" clause."
Upvotes: 2
Views: 927
Reputation: 2876
If you are doing the operations in the same method it's important to put the close in a finally statement of a try that envolves the open part of the stream. This ensures that in case of failure (Exception) the stream is allways closed if required
Bad sonar code:
OutputStream os=new FileOutputStream(file);
... // your code operations with os
// If something is going really bad here and ends in exception the
// stream will never be closed
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Better code:
OutputStream os = null;
try{
os = new FileOutputStream(file);
... // your code operations with os
} finally{
// The stream is allways closed at the end of the method execution
if(os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The best code (in case of Java 1.7 or upper)
try (OutputStream os = new FileOutputStream(file)){
... // your code operations with os
// The stream is allways closed at the end of the try block
}
Upvotes: 3
Reputation: 920
Try this instead. You do not do a close when using try with resources, that is automatically handled... i.e.
"The try-with-resources statement ensures that each resource is closed at the end of the statement."
try( OutputStream os=new FileOutputStream(file) ) {
....
}
Any resources declared within the brackets are closed automatically once the program flow has completed whether an exception is thrown or not..
Examples here : https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Upvotes: 1