Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java try with resource inputstream null check

Can somebody help on try with resource in java

try(InputStream inputStream = new FileInputStream(new File(some file)))
{
     if(inputStream == null)       //Line 3
     {
      }
}
catch(IOException e)
{
}

I want to know, is it necessary to check null on line 3. Will there be any situation or circumstances where inputStream can be null at line 3 ?

like image 941
Dark Matter Avatar asked Jul 02 '26 23:07

Dark Matter


2 Answers

Given your code, no:

InputStream inputStream = new FileInputStream(new File(some file)) will be executed before the contents of the try block. Either it will succeed, so inputStream will not be null, or it will fail, throwing an exception in the process, so the contents of the try block will never be executed.

like image 94
MyStackRunnethOver Avatar answered Jul 05 '26 13:07

MyStackRunnethOver


I want to know, is it necessary to check null on line 3.

No. As long as you keep the expression new FileInputStream(new File("path/to/file")), the result will be a non-null object of FileInputStream. The check on line 3 is unnecessary.

Will there be any situation or circumstances where inputStream can be null at line 3?

Yes. If you assign any expression that returns null to inputStream. It's not really practical since you can't do anything with the stream except for checking it on null. In that case, the check on line 3 may come in handy.

For example,

try (InputStream s = null) {}
catch (IOException e) {}
like image 32
Andrew Tobilko Avatar answered Jul 05 '26 13:07

Andrew Tobilko