Jump to content

Closing wrapped stream objects

- - - - -

  • Please log in to reply
2 replies to this topic

#1
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
When I'm done writing to an OutputStream, I always call close() to free up those resources. My question is, when nesting several OutputStream's inside wrapper classes, when you close the outermost object, does Java go through the nested classes and close them as well? In other words, is it okay to do this:

ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(output_file_name)));

oos.writeObject(some_serializable_object);

oos.close();

// Program goes on to do more stuff.

My question is, has the innermost FileOutputStream been closed? Or are those file resources still active at this point?

or is it more proper to do this:

FileOutputStream fos = new FileOutputStream(output_file_name);

GZIPOutputStream gzos = new GZIPOutputStream(fos);

ObjectOutputStream oos = new ObjectOutputStream(gzos);


oos.writeObject(some_serializable_object);


oos.close();

gzos.close();

fos.close();


// Program goes on to do more stuff.


Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
close() automatically closes all inner streams, this allows you to make chained streams with temporary objects.
Citation
Wow I changed my sig!

#3
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Thanks for the tip.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users