2016-12-07 5 views
-2

ここにサンプルコードがあります。関数によって作成されたFileInputStreamは、コードがparentFunctionのtry/catchブロックが存在するときに自動的に閉じられますか?Java自動クローズ機能の動作

someOtherFunction()自体で明示的に閉じておく必要がありますか?

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 ; 
} 
+1

あなたがしよう、と '[のリソースを指定する必要があるだろう-resources'](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)ステートメントを自動的にクローズする –

答えて

0

try-with-resourceブロックでリソースを使用する必要があります。

AutoCloseableインタフェースのためのドキュメントをお読みください:オブジェクトがリソース指定ヘッダで宣言されたトライを有する資源ブロックを出るときAutoCloseableオブジェクトのhttps://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html

メソッドが自動的に呼び出されます。

0

それは、明示的someOtherFunction()方法で閉じ、または試し-と、リソースブロックで使用する必要があります

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

     // do something with the stream. 

    } // the stream is auto-closed 
} 
関連する問題