In my old code, I often used the following constructor idiom for convenience:
MyClass( InputStream input ) {
// do actual stuff
}
MyClass( String filename ) {
this( new FileInputStream(filename) )
}
This leads to Eclipse warning me of a "Potential resource leak: '<unassigned Closeable value>' may not be closed" in the explicit constructor invocation.
Usually, I would use a try-with block for the auto-closable FileInputStream, but this is not possible here since the invocation must always be the first statement in a constructor. That is, the following does not compile:
MyClass( InputStream input ) {
// do actual stuff
}
MyClass( String filename ) {
try( FileInputStream fis = new FileInputStream(filename) ) {
this( fis );
}
}
So, what would be the correct (and elegant?) way to use this idiom without the risk of a potential resource leak? Any help is appreciated.