Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What are streams and what does it mean to close one?  RSS feed

 
F Turner
Ranch Hand
Posts: 30
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I've always been a little confused by Java streams. I figure that they must be objects which are used to 'deliver' to an application, data (be it from a file, or maybe even a serialised object?) little by little as the application asks for it. However, if this is true, what does it mean to close a stream, and why can the system have only a finite number of them?
Thanks
 
Stephan van Hulst
Saloon Keeper
Posts: 6969
109
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to be a little bit more specific in your wording, since Java 8 there is a new type called Stream, which is very different from InputStream. Because you posted in the I/O forum, I'm going to assume you meant an InputStream.

Let's say you have a 2GB file; you don't want to load it all into memory in one go. InputStream models all the data from some source, but allows you to process it in small chunks at a time. Closing a stream means closing the source where the data comes from. If you have a FileInputStream, closing it will close the file handle. This is important, because typically operating systems don't allow an application to have many files open at the same time. A stream of data could also come from a network connection, and having many open connections is also not allowed. Not just the amount of open files or connections is important, but as long as your application doesn't close one, it can't be used by other applications.

Closing streams used to be hard work. You would have to use a try-finally statement around your code, then try to close the stream in the finally-clause, and when *that* threw an exception, you would have to catch it because it's bad to throw exceptions from finally-clauses. This is what it looked like:

That's a lot of boilerplate! In Java 7, they introduced the try-with-resources statement. If you do this, the JVM will automatically close your stream for you, and handle any exceptions that may occur when trying to close it:

Whew!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!