Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close multiple resources with AutoCloseable (try-with-resources)

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

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?

like image 441
asmb Avatar asked May 31 '15 02:05

asmb


People also ask

Can we use multiple resources in try with resources?

The ability to specify multiple resources in a single try-with-resources statement is a feature introduced in Java 7. But, it can be fraught with peril if not used carefully.

Does try with resources close connection?

The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.

How do you handle exceptions in trying with resources?

For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.

What is the difference between try and try with resources?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.


1 Answers

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

Relevant code excerpt from the linked 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());         }     } } 

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.

like image 87
augray Avatar answered Oct 06 '22 14:10

augray