尝试使用Java中的多个资源 [英] Try with multiple Resource in Java

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

问题描述

我是Java8的新手,我想知道对于AutoCloseable资源,我是否必须为每个resource添加一个try,否则它将与上面的代码一起使用

I am new in Java8, and I want to know if, for the AutoCloseable resource, I have to add a try for each resource, or it will work with the code above

try (Connection conn = getConnection();) {

            Statement stmt = conn.createStatement();

            ResultSet rset = stmt.executeQuery(sql);

            while (rset.next()) {
                TelefonicaDataVO vo = new TelefonicaDataVO();
                vo.setTelefonicaDataId(rset.getString("Telefonica_PSD_ID"));
                vo.setReceptionDate(nvl(rset.getTimestamp("CREATION_DATE")));
                vo.setMessage(nvl(rset.getString("MESSAGE")));
                ret.add(vo);
            }
        }

推荐答案

通过在 try 块中声明所有资源,可以尝试将资源与多个资源一起使用,并且在中引入了此功能> java 7 不在 java 8 中,如果有多个,您可以像下面这样

Try with resources can be used with multiple resources by declaring them all in the try block and this feature introduced in java 7 not in java 8 If you have multiple you can give like below

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

在此示例中,try-with-resources语句包含两个用分号分隔的声明: ZipFile BufferedWriter .当紧随其后的代码块终止时,无论是正常还是由于异常而终止,都将按此顺序自动调用BufferedWriter和ZipFile对象的close方法. 请注意,资源的close方法是按照其创建的相反顺序调用的..

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation..

有关更多信息,请参见文档

Please see documentation for more info

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

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