Java的Try-with-resources 功能
在Java, Try-with-resources语句是一个 try 语句,它在其中声明一个或多个资源。资源是一个对象,一旦你的程序使用它就必须关闭它。例如,文件资源或套接字连接资源。 try-with-resources 语句确保每个资源在语句执行结束时关闭。如果我们不关闭资源,可能会造成资源泄漏,并且程序可能会耗尽可用的资源。
您可以将任何对象作为实现Java.lang.AutoCloseable的资源传递,其中包括实现Java.io.Closeable 的所有对象。
这样,现在我们不需要添加额外的 finally 块来传递资源的结束语句。执行 try-catch 块后,资源将立即关闭。
语法: Try-with-resources
try(declare resources here) {
// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
例外:
当涉及到异常时,try-catch-finally 块和 try-with-resources 块是有区别的。如果 try 块和 finally 块中都抛出异常,则该方法返回 finally 块中抛出的异常。
对于 try-with-resources,如果在 try 块和 try-with-resources 语句中抛出异常,则该方法返回在 try 块中抛出的异常。 try-with-resources 抛出的异常被抑制,即我们可以说 try-with-resources 块抛出被抑制的异常。
现在,让我们讨论下面作为示例演示的两种可能场景,如下所示:
- 案例 1 :单一资源
- 案例 2:多个资源
示例 1:具有单个资源的 try-with-resources
Java
// Java Program for try-with-resources
// having single resource
// Importing all input output classes
import java.io.*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try (
// Creating an object of FileOutputStream
// to write stream or raw data
// Adding resource
FileOutputStream fos
= new FileOutputStream("gfgtextfile.txt")) {
// Custom string input
String text
= "Hello World. This is my java program";
// Converting string to bytes
byte arr[] = text.getBytes();
// Text written in the file
fos.write(arr);
}
// Catch block to handle exceptions
catch (Exception e) {
// Display message for the occured exception
System.out.println(e);
}
// Display message for successful execution of
// program
System.out.println(
"Resource are closed and message has been written into the gfgtextfile.txt");
}
}
Java
// Java program for try-with-resources
// having multiple resources
// Importing all input output classes
import java.io.*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
// Writing data to a file using FileOutputStream
// by passing input file as a parameter
try (FileOutputStream fos
= new FileOutputStream("outputfile.txt");
// Adding resouce
// Reading the stream of character from
BufferedReader br = new BufferedReader(
new FileReader("gfgtextfile.txt"))) {
// Declaring a string holding the
// stream content of the file
String text;
// Condition check using readLine() method
// which holds true till there is content
// in the input file
while ((text = br.readLine()) != null) {
// Reading from input file passed above
// using getBytes() method
byte arr[] = text.getBytes();
// String converted to bytes
fos.write(arr);
// Copying the content of passed input file
// 'inputgfgtext' file to outputfile.txt
}
// Display message when
// file is successfully copied
System.out.println(
"File content copied to another one.");
}
// Catch block to handle generic exceptions
catch (Exception e) {
// Display the exception on the
// console window
System.out.println(e);
}
// Display message for successful execution of the
// program
System.out.println(
"Resource are closed and message has been written into the gfgtextfile.txt");
}
}
输出:
Resource are closed and message has been written into the gfgtextfile.txt
示例 2: try-with-resources 具有多个资源
Java
// Java program for try-with-resources
// having multiple resources
// Importing all input output classes
import java.io.*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
// Writing data to a file using FileOutputStream
// by passing input file as a parameter
try (FileOutputStream fos
= new FileOutputStream("outputfile.txt");
// Adding resouce
// Reading the stream of character from
BufferedReader br = new BufferedReader(
new FileReader("gfgtextfile.txt"))) {
// Declaring a string holding the
// stream content of the file
String text;
// Condition check using readLine() method
// which holds true till there is content
// in the input file
while ((text = br.readLine()) != null) {
// Reading from input file passed above
// using getBytes() method
byte arr[] = text.getBytes();
// String converted to bytes
fos.write(arr);
// Copying the content of passed input file
// 'inputgfgtext' file to outputfile.txt
}
// Display message when
// file is successfully copied
System.out.println(
"File content copied to another one.");
}
// Catch block to handle generic exceptions
catch (Exception e) {
// Display the exception on the
// console window
System.out.println(e);
}
// Display message for successful execution of the
// program
System.out.println(
"Resource are closed and message has been written into the gfgtextfile.txt");
}
}
输出:
File content copied to another one.
Resource are closed and message has been written into the gfgtextfile.txt