Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sense could it make not to close an InputStream after it ended?

InputStream implements Closeable.

I understand, that closing an InputStream which not ended yet, could make sense to free some underlying resources, and, leaving it open, could make sense to let other methods continue to read from it.

But, what sense could it have not to close an InputStream after it ended?
And if it doesn't make sense, why reaching the end of an InpuntStream does not imply closing then?

Same question would apply to Reader.

like image 528
java.is.for.desktop Avatar asked Sep 08 '10 12:09

java.is.for.desktop


2 Answers

mark() and reset() allow you to "go back" in some implementations of the interface.

This is useful when implementing parsers and matching regexps as you usually want to lookahead.

like image 196
gpeche Avatar answered Oct 14 '22 20:10

gpeche


In response to your comment to org.life.java

I know, and the question was: why an end of an InputStream does not imply close()?

Because, for some streams, you can rewind them and start reading again. For others, e.g. Sockets, it's not possible, but they have to obey the contract rules.

Also, because that's how you should close stream ( exception handling not shown ):

InputStream stream = openMethod( );

try
{
   consumeMethod( stream );
}
finally
{
   stream.close( );
}

In other words, you should release acquired resources regardless whether you totally consumed the stream or not.

like image 42
Alexander Pogrebnyak Avatar answered Oct 14 '22 19:10

Alexander Pogrebnyak