1. 程式人生 > >JDK1.7新特性--try-with-resources

JDK1.7新特性--try-with-resources

簡介

try-with-resources語句是一個宣告一個或多個資源的try語句。 資源是一個物件,必須在程式完成後關閉它。 try-with-resources語句確保在語句結束時關閉每個資源。 實現java.lang.AutoCloseable的任何物件(包括實現java.io.Closeable的所有物件)都可以用作資源。

以下示例從檔案中讀取第一行。 它使用BufferedReader例項從檔案中讀取資料。 BufferedReader是一個在程式完成後必須關閉的資源:

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

JDK1.7之前的做法

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
    return br.readLine();
  } finally {
    if (br != null) br.close();
  }
}

可以在try-with-resources語句中宣告一個或多個資源。 以下示例檢索zip檔案zipFileName中打包的檔案的名稱,並建立包含這些檔名稱的文字檔案:

public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {

    java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
    java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with try-with-resources statement

    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {

      // Enumerate each entry

      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

        // Get the entry name and write it to the output file

        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
      }
    }
  }

注意:try-with-resources語句可以像普通的try語句一樣有catch和finally塊。 在try-with-resources語句中,在宣告的資源關閉後執行任何catch或finally塊。