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.
Firstly, FileHandler
class doesn't implement AutoCloseable
interface.
So, you can't use try-with-resources
on FileHandler
.
Therefore, you have to call the close()
method explicitly.
So, you have to go for the first approach you took.
public class Example {
private static Logger logger = Logger.getLogger("...");
public static void main(String[] args) {
FileHandler fh = null;
try {
fh = new FileHandler("Test.log");
logger.addHandler(fh);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fh != null) {
fh.close();
}
}
}
}
You can try creating your own custom Filehandler
class and implement AutoCloseable
interface in that.
For example :
class CustomFileHandler implements AutoCloseable {
private FileHandler fileHandler;
public CustomFileHandler(FileHandler fileHandler) {
this.setFileHandler(fileHandler);
}
@Override
public void close() throws Exception {
if (fileHandler != null) {
fileHandler.close();
}
}
public FileHandler getFileHandler() {
return fileHandler;
}
private void setFileHandler(FileHandler fileHandler) {
this.fileHandler = fileHandler;
}
}
public class Example {
private static Logger logger = Logger.getLogger("...");
public static void main(String[] args) {
try (CustomFileHandler fh = new CustomFileHandler(new FileHandler("Test.log"))) {
logger.addHandler(fh.getFileHandler());
........
} catch (Exception e) {
e.printStackTrace();
}
}
}