Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use try-with-resources with an InputStream that has already been created?

Like this:

public void myMethod(InputStream fileIn){
    try (InputStream in = fileIn)  {
        do stuff....
    }
}

It seems to work. Is it safe?

like image 467
mal Avatar asked Dec 13 '22 13:12

mal


1 Answers

It seems to work

It will do if you add InputStream (or some supertype of InputStream) before in: the language spec requires you either to declare a variable for each resource.

try (InputStream in = fileIn) { ... }

or just refer directly to fileIn, in Java 9+:

try (fileIn) { ... }

And there's no reason why it shouldn't work: with the variable declaration form, you are assigning an expression to the variable (a new class, the result of a method invocation, an array element etc). The resource can't see if it is getting a "new" instance or not: it's just a thing with a value of the correct type.

is it safe?

Depends what exactly you mean by "safe".

It is certainly safe in the sense that it will work without error in this code, and in.close() will be invoked at the end of the block.

However, it violates the rule of thumb that "if you didn't open a stream, don't close it". As such, it might be unsafe in the sense that it causes unexpected failures in other parts of the program that expect the stream still to be open after invoking the method.

like image 163
Andy Turner Avatar answered Jan 30 '23 07:01

Andy Turner