English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In diesem Tutorial werden wir lernen, wie man try-with-resources-Anweisung schließt Ressourcen automatisch ab.
try-with-resources-Anweisung schließt alle Ressourcen automatisch am Ende des Satzes ab. Ressourcen sind Objekte, die am Ende des Programms geschlossen werden müssen.
Die Syntax ist:
try (resource declaration) { // Verwendung der Ressource } catch (ExceptionType e1) { // catch block }
Aus der obigen Syntax geht hervor, dass wir try-with-resources-Anweisung:
Ressourcen in der try-Klausel deklarieren und instanziieren.
Alle möglichen Ausnahmen, die beim Schließen der Ressourcen auftreten können, müssen spezifiziert und behandelt werden.
Hinweis:try-with-resources-Anweisung, die alle Ressourcen, die das Interface AutoCloseable implementieren, schließt, ansehen.
Lassen Sie uns die Implementierung von try-with-Beispiel für die resources-Anweisung.
import java.io;*; class Main { public static void main(String[] args) { String line; try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { while ((line = br.readLine()) != null) { System.out.println("Line =>")}+line); } } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } } }
Wenn die Datei test.txt nicht gefunden wird, wird ausgegeben.
IOException im try-with-resources block => test.txt (No such file or directory)
Wenn die Datei test.txt gefunden wird, wird ausgegeben.
Entering try-with-resources block Line => test line
In diesem Beispiel lesen wir Daten aus der Datei test.txt mit der Instanz BufferedReader.
In try-with-Der Aufruf und die Instanziierung von BufferedReader in der resources-Anweisung stellt sicher, dass die Instanz geschlossen wird, egal ob der try-Block normal abgeschlossen wird oder eine Ausnahme ausgelöst wird.
如果发生异常,则可以使用异常处理块或throws关键字对其进行处理。
在上面的示例中,在以下情况下可以从try-with-resources语句引发异常:
找不到test.txt文件。
关闭BufferedReader对象。
也可以从try块中引发异常,因为文件读取可能随时因多种原因而失败。
如果从try块和try-with-resources语句都抛出异常,则会抛出try块中的异常,并抑制try-with-resources语句中的异常。
In Java 7和更高版本中,可以通过Throwable.getSuppressed()从try块引发的异常中调用方法来检索抑制的异常。
此方法返回所有抑制的异常的数组。我们在catch块中得到了抑制的异常。
catch (IOException e) { System.out.println("Thrown exception=>" + e.getMessage()); Throwable[] suppressedExceptions = e.getSuppressed(); for (int i = 0; i < suppressedExceptions.length; i++) { System.out.println("Suppressed exception=>" + suppressedExceptions[i]); } }
这是使用try-with-resources的优点:
In Java 7在引入此功能之前,我们必须使用该finally块来确保关闭资源以避免资源泄漏。
这是一个类似于示例1的程序。但是,在此程序中,我们使用了finally块来关闭资源。
import java.io;*; class Main { public static void main(String[] args) { BufferedReader br = null; String line; try { System.out.println("Eingang in den try-Block"); br = new BufferedReader(new FileReader("test.txt")); while ((line = br.readLine()) != null) { System.out.println("Line =>")}+line); } } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } finally { System.out.println("进入 finally 块"); try { if (br != null) { br.close(); } } catch (IOException e) { System.out.println("IOException in finally block =>"+e.getMessage()); } } } }
输出结果
进入try 块 Line => line from test.txt 文件 进入 finally 块
从上面的示例可以看出,使用finally块来清理资源使代码更加复杂。
您注意到finally块中的try ... catch块吗? 这是因为在关闭此finally块内的BufferedReader实例时也可能发生IOException,因此也将其捕获并处理。
try-with-resources语句执行自动资源管理。我们不需要显式关闭资源,因为JVM会自动关闭它们。这使代码更具可读性,更易于编写。
我们可以try-with-resources使用分号将多个资源分开,从而在语句中声明多个资源;
import java.io;*; import java.util;*; class Main { public static void main(String[] args) throws IOException { try (Scanner scanner = new Scanner(new File("testRead.txt"))) { PrintWriter writer = new PrintWriter(new File("testWrite.txt")) { while (scanner.hasNext()) { writer.print(scanner.nextLine()); } } } }
Wenn beim Ausführen des Programms keine Ausnahmen generiert werden, liest das Scanner-Objekt eine Zeile aus der Datei testRead.txt und schreibt sie in die neue Datei testWrite.txt.
Make multiple declarations when trying-with-The resources statement closes these resources in the opposite order. In this example, the PrintWriter object is closed first, followed by the Scanner object.
In Java 7In, this try-with-The resources statement has a limitation. The resource needs to be declared locally within its block.
try (Scanner scanner = new Scanner(new File("testRead.txt"))) { // code }
If we are in Java 7If the resource is declared outside the block, an error message will be thrown.
Scanner scanner = new Scanner(new File("testRead.txt")); try (scanner) { // code }
To resolve this error, Java 9 Improved this try-with-The resources statement, so that even if the resource reference is not declared locally, it can be used. The code now will execute without throwing any compilation errors.