Java 尝试使用资源输入流空检查
Java try with resource inputstream null check
有人可以帮忙试试 java
中的资源吗
try(InputStream inputStream = new FileInputStream(new File(some file)))
{
if(inputStream == null) //Line 3
{
}
}
catch(IOException e)
{
}
我想知道,是否需要在第3行检查null。是否有任何情况或情况inputStream在第3行可以为null?
鉴于您的代码,否:
InputStream inputStream = new FileInputStream(new File(some file))
将在 try
块的内容之前执行。要么会成功,所以inputStream
不会是null
,要么会失败,在过程中抛出异常,所以try
块的内容永远不会被执行。
I want to know, is it necessary to check null on line 3.
没有。只要保留表达式 new FileInputStream(new File("path/to/file"))
,结果将是 FileInputStream
的非空对象。第 3 行的检查是不必要的。
Will there be any situation or circumstances where inputStream can be null at line 3?
是的。如果将 returns null
的任何表达式分配给 inputStream
。这不是很实用,因为除了检查它是否为 null 之外,你不能对流做任何事情。那样的话,第3行的check可能就派上用场了。
例如,
try (InputStream s = null) {}
catch (IOException e) {}
有人可以帮忙试试 java
中的资源吗try(InputStream inputStream = new FileInputStream(new File(some file)))
{
if(inputStream == null) //Line 3
{
}
}
catch(IOException e)
{
}
我想知道,是否需要在第3行检查null。是否有任何情况或情况inputStream在第3行可以为null?
鉴于您的代码,否:
InputStream inputStream = new FileInputStream(new File(some file))
将在 try
块的内容之前执行。要么会成功,所以inputStream
不会是null
,要么会失败,在过程中抛出异常,所以try
块的内容永远不会被执行。
I want to know, is it necessary to check null on line 3.
没有。只要保留表达式 new FileInputStream(new File("path/to/file"))
,结果将是 FileInputStream
的非空对象。第 3 行的检查是不必要的。
Will there be any situation or circumstances where inputStream can be null at line 3?
是的。如果将 returns null
的任何表达式分配给 inputStream
。这不是很实用,因为除了检查它是否为 null 之外,你不能对流做任何事情。那样的话,第3行的check可能就派上用场了。
例如,
try (InputStream s = null) {}
catch (IOException e) {}