Basic|Java try-with-resources

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
不需要finally中关闭,直接在try中写resource,resource可以是实现了java.lang.AutoClosable和java.io.Closable的所有类
【Basic|Java try-with-resources】

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(); } }


    推荐阅读