English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
try-with-resources é no JDK 7 Nova mecanismo de tratamento de exceções no try-catch o recurso usado no bloco de exceção.-with-a declaração resources garante que cada recurso seja fechado no final da sentença. Todos os objetos que implementam a interface java.lang.AutoCloseable (onde inclui todos os objetos que implementam java.io.Closeable) podem ser usados como recursos.
try-with-declaração resources no JDK 9 Se você já tiver um recurso que é final ou equivalente a um variável final, você pode usá-lo no try-with-usa a variável na declaração resources, sem precisar declarar no try-with-declara uma nova variável em uma declaração resources.
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (BufferedReader br1 = br) { return br1.readLine(); } } }
O resultado de saída é:
test
No exemplo acima, precisamos declarar o recurso br dentro do bloco try1depois disso, para poder usá-lo.
em Java 9 não precisamos declarar o recurso br1 pode usá-lo e obter o mesmo resultado.
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (br) { return br.readLine(); } } }
A saída de execução é:
test
Use try para lidar com recursos que devem ser fechados-with-resources por try-A sentença finally. O código gerado é mais conciso, mais claro e gera exceções mais úteis. Substitua o try-with-A sentença resources torna mais fácil escrever código que deve fechar recursos, sem erros, em vez de usar try-A sentença finally é realmente impossível.