I have a class where on the one hand, it feels right to return an InputStream from a public method, e.g.
public class MyClass {
private File _file;
...
public InputStream getInputStream() {
return new FileInputStream( _file );
}
}
However, I’m also very cautious about doing this, as it puts the onus on the caller to close this stream. What ways can I potentially avoid this problem?
Depends on why this is a problem in your eyes. If you absolutely must return an
InputStreamand the file in question is not too large, you could buffer the entire file into a byte array, close the original stream andreturn new ByteArrayInputStream(buf). Closing aByteArrayInputStreamis not necessary (and in fact has no effect).However, if it “feels right” to return an
InputStream, does it not make sense that the caller should be expecting anInputStream, and all that goes with it, including the necessity of closing the stream when finished?