8

私は、1 つのことを行う次の Java クラスを持っていますconfig.properties

を閉じるときが来たらfileInputStream、Wikipedia で、finally ブロックに入れておくとよいと読んだと思います。正直に言うと、try/catch ブロックで問題なく動作するからです。

fileInputStream.close()最終セクションに入るための修正を教えてもらえますか?

ConfigProperties.java パッケージ ベース。

import java.io.FileInputStream;
import java.util.Properties;

public class ConfigProperties {

    public FileInputStream fileInputStream;
    public String property;

    public String getConfigProperties(String strProperty) {

        Properties configProperties = new Properties();
        try {

            fileInputStream = new FileInputStream("resources/config.properties");
            configProperties.load(fileInputStream);
            property = configProperties.getProperty(strProperty);
            System.out.println("getConfigProperties(" + strProperty + ")");

            // use a finally block to close your Stream.
            // If an exception occurs, do you want the application to shut down?

        } catch (Exception ex) {
            // TODO
            System.out.println("Exception: " + ex);
        }
        finally {
            fileInputStream.close();
        }

        return property;
    }
}

解決策は、Eclipse が提案するとおりに実行し、finally ブロックでこれを実行するだけですか?

finally {
    try {
        fileInputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
4

3 に答える 3

22

はい、それが一般的な Java 7 以前のソリューションです。ただし、Java 7 の導入により、ブロックの終了時に宣言されたリソースを自動的に閉じるtry-with-resourceステートメントが追加されました。try

try (FileInputStream fileIn = ...) {
    // do something
} // fileIn is closed
catch (IOException e) {
    //handle exception
}
于 2012-07-24T00:13:35.407 に答える
10

FileInputStream.close()は IOException をスローし、finally{} ブロックは例外をキャッチしないためです。したがって、コンパイルするには、それをキャッチするか宣言する必要があります。Eclipse の提案は問題ありません。finally{} ブロック内で IOException をキャッチします。

于 2012-07-24T00:12:42.623 に答える
10

標準的なアプローチは次のとおりです。

FileInputStream fileInputStream = null;
try {
    fileInputStream = new FileInputStream(...);
    // do something with the inputstream
} catch (IOException e) {
    // handle an exception
} finally { //  finally blocks are guaranteed to be executed
    // close() can throw an IOException too, so we got to wrap that too
    try {
        if (fileInputStream != null) {
            fileInputStream.close();
        }        
    } catch (IOException e) {
        // handle an exception, or often we just ignore it
    }
}
于 2012-07-24T00:18:37.320 に答える