Java 资源试用
原文:https://www.studytonight.com/java/try-with-resource-statement.php
Try with resource 是 Java 的一个新特性,在 Java 7 中引入,在 Java 9 中进一步改进。这个特性为资源管理的异常处理增加了另一种方式。也称自动资源管理。它使用自动关闭接口自动关闭资源..
资源可以是任何类似的:文件、连接等,我们不需要显式关闭它们,JVM 会自动关闭它们。
假设,我们运行一个 JDBC 程序来连接数据库,然后我们必须创建一个连接,并在任务结束时关闭它。但是在尝试使用资源的情况下,我们不需要关闭连接,JVM 将使用自动关闭接口自动关闭连接。
尝试资源语法
try(resource-specification(there can be more than one resource))
{
//use the resource
}
catch()
{
// handler code
}
这个 try 语句包含一个括号,其中声明了一个或多个资源。任何实现java.lang.AutoCloseable
或java.io.Closeable
的对象,都可以作为参数传递给 try 语句。资源是程序中使用的对象,在程序完成后必须关闭。 try-with-resources 语句确保每个资源在 try 块的语句结束时关闭。我们不必显式关闭资源。
资源语句不使用try
的例子
让我们看看这样的场景:我们没有使用 try-with-resource 块,而我们使用的是普通的 try 块,这就是为什么我们需要显式关闭文件引用。
import java.io.*;
class Demo
{
public static void main(String[] args)
{
try {
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br = new BufferedReader(new FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close(); //closing BufferedReader stream
}
catch(IOException ie)
{
System.out.println("I/O Exception "+ie);
}
}
}
I/O 异常 Java . io . file notfoundexception:d:\ my file . txt(没有这样的文件或目录)
带有资源语句的示例try
在这里,我们使用 try-with-resource 来打开文件,并看到我们没有使用 close 方法来关闭文件连接。
import java.io.*;
class Demo
{
public static void main(String[] args)
{
try(BufferedReader br = new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str = br.readLine()) != null)
{
System.out.println(str);
}
}
catch(IOException ie)
{
System.out.println("I/O Exception "+ie);
}
}
}
注意:在上面的例子中,我们不需要显式调用close()
方法来关闭 BufferedReader 流。
尝试使用资源–Java 9
在 Java 7 中,引入了 try-with-resource,其中资源是在 try 块中创建的。Java 7 的限制是,在外部创建的连接对象不能在尝试资源内部引用。
在 Java 9 中,这个限制被消除了,所以现在我们可以在 try-with-resource 之外创建对象,然后在里面引用而不会出错。
例子
import java.io.*;
class Demo
{
public static void main(String[] args) throws FileNotFoundException
{
BufferedReader br = new BufferedReader(new FileReader("d:\\myfile.txt"));
try(br) // resource is declared outside the try
{
String str;
while((str = br.readLine()) != null)
{
System.out.println(str);
}
}
catch(IOException ie)
{
System.out.println("I/O Exception "+ie);
}
}
}
需要记住的要点
- 资源是程序中的一个对象,它必须在程序完成后关闭。
- 任何实现
java.lang.AutoCloseable
或java.io.Closeable
的对象都可以作为参数传递给 try 语句。 - try-with-resources 语句中声明的所有资源将在 try 块退出时自动关闭。没有必要显式关闭它。
- 我们可以在 try 语句中编写多个资源。
- 在 try-with-resources 语句中,任何 catch 或 finally 块都是在已声明的资源关闭后运行的。