尝试在 Java 中使用多个资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47175526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Try with multiple Resource in Java
提问by en Lopes
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
我是新来的Java8
,我想知道对于AutoCloseable
资源,我是否必须try
为每个添加一个resource
,或者它可以与上面的代码一起使用
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);
}
}
回答by vts
Try with resources can be used with multiple resources by declaring them all in the try
block and this feature introduced in java 7not in java 8If you have multiple you can give like below
Try with resources 可以通过在try
块中声明它们来与多个资源一起使用,并且这个特性在java 7 中引入而不是在java 8如果你有多个你可以像下面这样
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: ZipFileand 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..
在此示例中,该try-with-resources
语句包含两个用分号分隔的声明:ZipFile和BufferedWriter。当直接跟随它的代码块终止时,无论是正常情况还是由于异常,BufferedWriter 和 ZipFile 对象的 close 方法将按此顺序自动调用。请注意,资源的 close 方法的调用顺序与它们的创建顺序相反。.
Please see documentationfor more info
请参阅文档了解更多信息