Java try-with-resources

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

不需要finally中关闭,直接在try中写resource,resource可以是实现了java.lang.AutoClosable和java.io.Closable的所有类

 

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

 

你可能感兴趣的:(Basic,Java)