-2

I have a sample code here. Will the FileInputStream created by the function, get automatically closed when the code exists the try/catch block of parentFunction ?

Or does it need to be explicitly closed in the someOtherFunction() itself ?

private void parentFunction() {

   try {
       someOtherFunction();
   } catch (Exception ex) {
    // do something here

   } 

}

private void someOtherFunction() {
    FileInputStream stream = new FileInputStream(currentFile.toFile());

    // do something with the stream.

    // return, without closing the stream here
    return ;
}
CodeKata
  • 572
  • 4
  • 8
  • 1
    You'd need to specify the resource in a [`try-with-resources`](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement in order for it to be auto closed – Vince Dec 07 '16 at 21:17

2 Answers2

0

You have to use the resource with try-with-resource block.

Please read docs for AutoCloseable interface: https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html

method of an AutoCloseable object is called automatically when exiting a try-with-resources block for which the object has been declared in the resource specification header.

pnkkr
  • 337
  • 3
  • 15
0

It needs to either be explicitly closed in the someOtherFunction() method, or used in a try-with-resources block:

private void someOtherFunction() {
    try (FileInputStream stream = new FileInputStream(currentFile.toFile())) {

        // do something with the stream.

    } // the stream is auto-closed
}
Jason
  • 11,744
  • 3
  • 42
  • 46