[英]DataInputStream closing
When I pass a InputStream to this method, does it close that? 当我将InputStream传递给此方法时,它是否将其关闭?
public void foo(InputStream is) {
DataInputStream dis = new DataInputStream(is);
dis.close();
}
The superclass FilterInputStream redefines the close method as closing underlying inputstream too, so it will close the parameter is . 超类FilterInputStream也将close方法重新定义为close基础输入流,因此它将关闭参数is 。
Does that action affect the inputstream at the caller? 该操作会影响调用方的输入流吗?
Yes, the stream that is passed in will be closed. 是的,传入的流将被关闭。
Closing streams that you didn't open is hardly ever a good idea, so you should not close dis
in this method. 关闭未打开的流几乎不是一个好主意,因此您不应该使用此方法关闭
dis
。
DataInputStream
holds no system resources of its own, so not closing it will not cause any leaks. DataInputStream
不拥有自己的系统资源,因此不关闭它不会导致任何泄漏。 You can simply leave it open. 您可以将其保持打开状态。 Alternatively you can return it from the method so that the caller can close it.
或者,您可以从方法中返回它,以便调用者可以将其关闭。
Yes, DataInputStream
is a decorator-class over passed InputStream
is
. 是的,
DataInputStream
是传递的InputStream
is
的装饰器类。 It isn't a InputStream
it self. 它本身不是
InputStream
。
So Essentially DataInputStream.close
implies close
on underlying InputStream
. 因此从本质上讲
DataInputStream.close
意味着对基础InputStream
close
。
/** * Closes this input stream and releases any system resources * associated with the stream. * This * method simply performs <code>in.close()</code>. * * @exception IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ public void close() throws IOException { in.close(); }
The InputStream will be closed. InputStream将关闭。
Since Java SE 7 it is better to use try-with-resources so streams will be closed automatically. 从Java SE 7开始,最好使用try-with-resources,这样流将自动关闭。
You should close the InputStream in caller method only. 您应该仅在调用方方法中关闭InputStream。 Use Try Catch block whenever you are using any operation related to input or output streaming, if any of the stream remains open it will be handled by java
每当您使用与输入或输出流相关的任何操作时,请使用Try Catch块,如果任何流保持打开状态,它将由java处理
The class DataInputStream
implements Coseable
and AutoClose
interfaces so the method close
in class DataInputStream
closes this input stream and releases any system resources associated with the stream. DataInputStream
类实现Coseable
和AutoClose
接口,因此DataInputStream
类中的close
方法将关闭此输入流并释放与该流关联的所有系统资源。 This method simply performs in.close()
. 此方法仅执行
in.close()
。 Specified by close in interface Closeable
, close in interface AutoCloseable
Overrides close in class InputStream
. 由接口
Closeable
中的close指定,接口AutoCloseable
close在类InputStream
重写close。
Throws: IOException
- if an I/O error occurs. 抛出:
IOException
如果发生I / O错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.