使用 AutoCloseable 关闭多个资源(try-with-resources)

2024-01-03

我知道,如果资源实现了 AutoCloseable,则您尝试传递的资源将自动关闭。到目前为止,一切都很好。但是,当我有多个想要自动关闭的资源时,我该怎么办?套接字示例;

try (Socket socket = new Socket()) {
    input = new DataInputStream(socket.getInputStream());
    output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
} 

所以我知道套接字将被正确关闭,因为它是在 try 中作为参数传递的,但是输入和输出应该如何正确关闭?


Try with resources 可以通过在括号中声明所有资源来与多个资源一起使用。请参阅文档 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

链接文档中的相关代码摘录:

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

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.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());
        }
    }
}

如果你的对象没有实现AutoClosable (DataInputStream确实),或者必须在 try-with-resources 之前声明,那么关闭它们的适当位置是在finally块,链接文档中也提到了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AutoCloseable 关闭多个资源(try-with-resources) 的相关文章

随机推荐