淮南北京網站建設新網站如何推廣
屬于Java7的新特性。
經常會用try-catch來捕獲有可能拋出異常的代碼。如果其中還涉及到資源的使用的話,最后在finally塊中顯示的釋放掉有可能被占用的資源。
但是如果資源類已經實現了AutoCloseable這個接口的話,可以在try()括號中可以寫操作資源的語句(IO操作),會在程序塊結束時**自動釋放掉占用的資源**,不用再在finally塊中手動釋放了。
例子:
沒使用該特性
如果要釋放的資源多得話,判斷加catch占得篇幅大,不美觀也不精簡
用了這個特性后代碼可以精簡些
try-catch-finally
try-with-resources
----------------------------------------------------分割線---------------------------------------------------------------------
取自:https://jenkov.com/tutorials/java-exception-handling/try-with-resources.html
Using Multiple Resources
You can use multiple resources inside a Java try-with-resources block and have them all automatically closed. Here is an example of using multiple resources inside a try-with-resources block:
This example creates two resources inside the parentheses after the try keyword. An FileInputStream and a BufferedInputStream. Both of these resources will be closed automatically when execution leaves the try block.
Closing Order
The resources declared in a Java try-with-resources construct will be closed in reverse order of the order in which they are created / listed inside the parentheses. In the example in the previous section, first the will be closed, then the FileInputStream.
Custom AutoClosable Implementations
The Java try-with-resources construct does not just work with Java’s built-in classes. You can also implement the java.lang.AutoCloseable interface in your own classes, and use them with the try-with-resources construct.
The AutoClosable interface only has a single method called close(). Here is how the interface looks:
Any class that implements this interface can be used with the Java try-with-resources construct. Here is a simple example implementation:
The doIt() method is not part of the AutoClosable interface. It is there because we want to be able to do something more than just closing the object.
Here is an example of how the MyAutoClosable is used with the try-with-resources construct:
Here is the output printed to System.out when the method myAutoClosable() is called:
As you can see, try-with-resources is a quite powerful way of making sure that resources used inside a try-catch block are closed correctly, no matter if these resources are your own creation, or Java’s built-in components.
舉例
參考:
Java必須懂的try-with-resources
java知識大全
jenkov.com