try-with-resources: Does Java make any guarantees about the order of calls to .close()?

StackOverflow https://stackoverflow.com/questions/12136637

  •  28-06-2021
  •  | 
  •  

Domanda

When using a try-with-resources in Java 7, are there any guarantees about the order in which .close() is called?

Here's some sample code from Oracle showing this feature:

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

Both zf.close() and writer.close() will be called. Is the order guaranteed?

È stato utile?

Soluzione

It is in the opposite order of declaration, closing from the inside to the outside.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top