java - Try-with transfer ownership -


in java 7, there try-with syntax ensures objects inputstream closed in code paths, regardless of exceptions. however, variable declared in try-with block ("is") final.

try (inputstream = new fileinputstream("1.txt")) {     // stuff "is"     is.read();      // give "is" owner     someobject.setstream(is);      // release "is" ownership: doesn't work because final     = null; } 

is there concise syntax express in java? consider exception-unsafe method. adding relevant try/catch/finally blocks make method more verbose.

inputstream opentwofiles(string first, string second) {     inputstream is1 = new fileinputstream("1.txt");      // is1 leaked on exception     inputstream is2 = new fileinputstream("2.txt");      // can't use try-with because close is1 , is2     inputstream dual = new dualinputstream(is1, is2);     return dual; } 

obviously, can have caller open both files, placing them both in try-with block. 1 example of case want perform operation on resource before transferring ownership of object.

the try-with intended used in situation identified resource must never persist outside scope of try block.

if want use try-with construction, must change design follows:

  1. delete opentwofiles() method. value free.
  2. create constructor dualinputstream class takes 2 file names , creates 2 inputstreams. declare constructor throws ioexception , allow throw ioexceptions.
  3. use new constructor in try-with construct.

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -