使用AutoCloseable关闭多个资源(尝试使用资源) [英] Close multiple resources with AutoCloseable (try-with-resources)

查看:314
本文介绍了使用AutoCloseable关闭多个资源(尝试使用资源)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果资源实现了AutoCloseable,那么您通过try传递的资源将自动关闭。到现在为止还挺好。但是当我有几个我希望自动关闭的资源时,该怎么办?带插槽的示例;

I know that the resource you pass with a try, will be closed automatically if the resource has AutoCloseable implemented. So far so good. But what do I do when i have several resources that I want automatically closed. Example with sockets;

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

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

So I know the socket will be closed properly, because it's passed as a parameter in the try, but how should the input and output be closed properly?

推荐答案

通过在括号中声明所有资源,可以尝试使用多种资源。请参阅文档

Try with resources can be used with multiple resources by declaring them all in the parenthesis. See the documentation

相关代码摘录自链接文档:

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 块中,也在链接文档中提到。

If your objects don't implement AutoClosable (DataInputStream does), or must be declared before the try-with-resources, then the appropriate place to close them is in a finally block, also mentioned in the linked documentation.

这篇关于使用AutoCloseable关闭多个资源(尝试使用资源)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆