Java try/catch/finally best practices while acquiring/closing resources

后端 未结 8 1095
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:43

While working on a school project, I wrote the following code:

FileOutputStream fos;
ObjectOutputStream oos;
try {
    fos = new FileOutputStream(file);
             


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 14:27

    Current best practice for try/catch/finally involving objects that are closeable (e.g. Files) is to use Java 7's try-with-resource statement, e.g.:

    try (FileReader reader = new FileReader("ex.txt")) {
        System.out.println((char)reader.read());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    

    In this case, the FileReader is automatically closed at the end of the try statement, without the need to close it in an explicit finally block. There are a few examples here:

    http://ppkwok.blogspot.com/2012/11/java-cafe-2-try-with-resources.html

    The official Java description is at:

    http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

提交回复
热议问题