在 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()
都会被调用。订单有保障吗?
最佳答案
是in the opposite order of declaration ,从内到外闭合。
关于java-7 - try-with-resources:Java 是否对 .close() 的调用顺序做出任何保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12136637/