I'm having below code and creating log file using java.util.logging.FileHandler
.
In this scenario, I should manually close the resources in finally block.
try {
fh = new FileHandler("Test.log");
logger.addHandler(fh);
...
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fh!=null) { fh.close() };
}
This code works. Now, I thought that it may implement Autocloseable
interface. So, I decided to use try-with-resources
for FileHandler
so that the resources will be automatically closed (to remove manual job of closing the resources).
The code I tried is given below :
try(fh = new FileHandler("Test.log")) {
logger.addHandler(fh);
...
} catch (IOException e) {
e.printStackTrace();
}
But this code doesn't work.
It give an error saying that :
The resource type FileHandler does not implement java.lang.AutoCloseable'
How to close the file handler automatically using try-with-resources if possible ?
Do I need to close manually ? Or there is any other approach that I can take.