Java 教程

Java 控制语句

面向对象编程

Java 内置类

Java 文件处理

Java 错误和异常

Java 多线程

Java 同步

Java 网络

Java 集合

Java 接口

Java 数据结构

Java 集合算法

高级 Java

Java 杂项

Java API 和框架

Java 类参考

Java 有用资源

Java - 带资源的 try 语句



带资源的 try 语句

Java 的 try-with-resources 语句是一个try 语句,用于声明一个或多个资源,例如流、套接字、数据库、连接等。这些资源必须在程序完成时关闭。try-with-resources 语句在语句结束时关闭资源。

try-with-resources 功能是在 Java7 中引入的。try-with-resources 也可以替代try-catch-finally 用于资源对象。

try-with-resources 语句也称为“自动资源管理”,它是在 Java7 中引入的。如果您正在使用资源对象,则此语句可以替代 try-catch-finally 语句。

带资源的 try 语句的语法

要使用此语句,您只需在括号内声明所需的资源,并在块结束时自动关闭创建的资源。以下是 try-with-resources 语句的语法

try(resources declarations) {
    // use of the resources
}
catch(Exception e) {
    // exception handling
}

例如,使用 try-with-resources 打开文件

try(FileReader fr = new FileReader("file path")) {
   // use the resource
   } catch () {
      // body of catch 
   }
}

以下程序使用 try-with-resources 语句读取文件中的数据。

示例:Java 中的带资源的 try 语句

在此程序中,我们在 try with resources 语句中创建 FileReader 对象。FileReader fr,引用在 try 语句中声明,我们不需要记住在 finally 块中关闭它,因为它将由 JVM 自动关闭,因此不存在内存泄漏或连接丢失的可能性。

import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

   public static void main(String args[]) {
      try(FileReader fr = new FileReader("E://file.txt")) {
         char [] a = new char[50];
         fr.read(a);   // reads the contentto the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

具有多个资源的带资源的 try 语句

您还可以在 try 块中声明多个资源。请考虑以下示例:

// This example is to use Try with Resources 
// with multiple  Resources
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    // try block with multiple resources
    try (
      FileReader fileReader = new FileReader("file1.txt"); 
      BufferedReader bufferedReader = new BufferedReader(fileReader); 
      FileWriter fileWriter = new FileWriter("file2.txt"); 
      PrintWriter printWriter = new PrintWriter(fileWriter)
    ) {
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        // Read content line by line and write it 
        // to the output (file2.txt) file
        printWriter.println(line);
      }
      System.out.println("Content copied.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

示例:不使用带资源的 try 语句

在以下程序中,我们使用FileReader读取文件中的数据,并使用 finally 块关闭它。在此程序中,我们在 try 块中创建 FileReader 对象。FileReader fr,引用在 try 块之外声明,以便在 try 块之外访问它,我们需要记住在 finally 块中或程序退出之前关闭它,以避免内存泄漏或连接丢失的可能性。

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadData_Demo {

   public static void main(String args[]) {
      FileReader fr = null;		
      try {
         File file = new File("file.txt");
         fr = new FileReader(file); char [] a = new char[50];
         fr.read(a);   // reads the content to the array
         for(char c : a)
         System.out.print(c);   // prints the characters one by one
      } catch (IOException e) {
         e.printStackTrace();
      }finally {
         try {
            fr.close();
         } catch (IOException ex) {		
            ex.printStackTrace();
         }
      }
   }
}

带资源的 try 语句:要点

在使用 try-with-resources 语句时,请牢记以下几点。

  • 要将类与 try-with-resources 语句一起使用,它必须实现AutoCloseable接口,并且其close()方法会在运行时自动调用。

  • 您可以在 try-with-resources 语句中声明多个类。

  • 当您在 try-with-resources 语句的 try 块中声明多个类时,这些类将以相反的顺序关闭。

  • 除了在括号内声明资源之外,其他所有内容都与 try 块的普通 try/catch 块相同。

  • 在 try 块开始之前,try 中声明的资源会被实例化。

  • 在 try 块中声明的资源隐式声明为 final。

Java 9 中带资源的 try 语句的改进

在 Java 9 之前,资源需要在 try 之前或 try 语句内部声明,如下面的示例所示。在此示例中,我们将使用 BufferedReader 作为资源来读取字符串,然后关闭 BufferedReader。

Java 9 之前

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();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

test

在这里,我们需要在 try 语句中声明一个资源 br1,然后使用它。在 Java9 中,我们不再需要声明 br1,以下程序将给出相同的结果。

Java 9 及以后版本

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();
      }
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

test
广告

© . All rights reserved.