try-with-resources:Java是否对.close()的调用顺序做出任何保证?

时间:2012-08-27 05:30:10

标签: java-7 try-with-resources

在Java 7中使用try-with-resources时,是否有关于.close()被调用的顺序的保证?

以下是来自Oracle的一些示例代码,显示了此功能:

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

将调用zf.close()writer.close()。订单有保证吗?

1 个答案:

答案 0 :(得分:4)

in the opposite order of declaration,从内到外关闭。