Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is going to happend if i don't close streams?

 
Mihai Lita
Ranch Hand
Posts: 36
Firefox Browser Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,
I have a question, suppose i have this code :


what will happend if i comment the oos.close() line?

Thank you.
 
Rob Camick
Ranch Hand
Posts: 2542
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Data only gets written to the file when the buffer is full not every time to you invoke a write(...) method. One of the functions of the close() method is to flush the buffer to make sure all the data is written. I'm sure there are other issues as well.
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... which means it depends on the Stream (or Writer) implementation: there could well be stream implementations that perform no buffering internally, while others may do so (obviously, BufferedOutputStream does). In both cases I would not necessarily expect to find that mentioned in the javadocs.
 
Mihai Lita
Ranch Hand
Posts: 36
Firefox Browser Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, in the book i`m reading it was mentioned that buffer only write when the buffer is full that was all it was mentioned. I didn`t knew close() flushes the buffer, is there any other way we can force a buffer to write before it`s full?


The book is Head First Java,2nd ed.
 
Eric Mission
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java I/O API has top-level objects- Reader and Writer which both have some useful methods to inherited classes like BufferedReader or BufferedWriter.

From the Java I/O Streams-

Some other notable methods in the top-level classes include skip(int), mark(int), reset(), available(), ready() and flush(), these are described below...

...The flush() method simply writes out any buffered characters (or bytes) to the destination (for example, file, or socket).



Closing any type of I/O stream (file or socket) is a good habit to follow for several reasons- freeing up system resources, freeing up the heap for other objects, preventing file locks for other applications or for multi-threaded applications and so many more reasons.
 
Rob Camick
Ranch Hand
Posts: 2542
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> is there any other way we can force a buffer to write before it`s full?

Check out the FileOutputStream API to see if any method seems appropriate.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic