Try with multiple Resource in Java [duplicate]

两盒软妹~` 提交于 2019-12-03 19:28:58

问题


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

回答1:


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

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



来源:https://stackoverflow.com/questions/47175526/try-with-multiple-resource-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!