I have been working with try-with-resources statement.
try(FileReader rd = new FileReader("Test.txt");){}
catch (Exception e) {e.printStackTrace();}
The benefit of using try with resources is mainly to do with avoiding to specify the finally block to close out resources.
Thats where my research process kicked in.
After doing some debugging, I found out the FileReader extends InputStreamReader. Inside FileReader class this constructor called
public FileReader(File file) throws FileNotFoundException {
super(new FileInputStream(file));
}
which creates an object of FileInputStream class. FileInputStream extends InputStream which implements Closeable interface.
Inside FileInputStream class close method is being called as below and doing what it needs to do to close out resources using native method.
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
channel.close();
}
fd.closeAll(new Closeable() {
public void close() throws IOException {
close0();
}
});
}
So I understood this is how the close method is being called.
Now what I fail to understand when I implement the Closeable interface with some custom class directly such as
public class MyClass implements Closeable
{
public void close()
{
System.out.println("connection closed...");
}
}
and use it like so
try(MyClass rd = new MyClass();)
{}
catch (Exception e)
{e.printStackTrace();}
It is still calling the the close method in custom class MyClass automatically without me calling it explicitly. When I ran through debug it is going into FileInputStream class which extends InputStream class which implements Closeable interface. And then finally this method is being called
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
if (channel != null) {
channel.close();
}
fd.closeAll(new Closeable() {
public void close() throws IOException {
close0();
}
});
}
Can someone please explain to me how FileInputStream instance/object is being created?
Thanks in advance.