java - If it safe to return an InputStream from try-with-resource -
this question has answer here:
is safe return input stream try-with-resource statement handle closing of stream once caller has consumed it?
public static inputstream example() throws ioexception { ... try (inputstream = ...) { return is; } }
it's safe, closed, don't think particularly useful... (you can't reopen closed stream.)
see example:
public static void main(string[] argv) throws exception { system.out.println(example()); } public static inputstream example() throws ioexception { try (inputstream = files.newinputstream(paths.get("test.txt"))) { system.out.println(is); return is; } }
output:
sun.nio.ch.channelinputstream@1db9742 sun.nio.ch.channelinputstream@1db9742
the (same) input stream returned (same reference), closed. modifying example this:
public static void main(string[] argv) throws exception { inputstream = example(); system.out.println(is + " " + is.available()); } public static inputstream example() throws ioexception { try (inputstream = files.newinputstream(paths.get("test.txt"))) { system.out.println(is + " " + is.available()); return is; } }
output:
sun.nio.ch.channelinputstream@1db9742 1000000 exception in thread "main" java.nio.channels.closedchannelexception @ sun.nio.ch.filechannelimpl.ensureopen(filechannelimpl.java:109) @ sun.nio.ch.filechannelimpl.size(filechannelimpl.java:299) @ sun.nio.ch.channelinputstream.available(channelinputstream.java:116) @ sandbox.app.main.main(main.java:13)
Comments
Post a Comment