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


i know resource pass try, closed automatically if resource has autocloseable implemented. far good. do when have several resources want automatically closed. example sockets;

try (socket socket = new socket()) {     input = new datainputstream(socket.getinputstream());     output = new dataoutputstream(socket.getoutputstream()); } catch (ioexception e) { }  

so know socket closed properly, because it's passed parameter in try, how should input , output closed properly?

try resources can used multiple resources declaring them them in parenthesis. see documentation

relevant code excerpt 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 , create output file      // 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         (java.util.enumeration entries =                                 zf.entries();     entries.hasmoreelements();) {             // entry name , write 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 objects don't implement autoclosable (datainputstream does), or must declared before try-with-resources, appropriate place close them in finally block, mentioned in linked documentation.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -