Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ocurrio un error:java.io.IOException: Stream closed

 
Marcel Chasiguasin
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear all,

why is the following code returning this exception Ocurrio un error:java.io.IOException: Stream closed???
 
Tomasz Sochanski
Ranch Hand
Posts: 47
Eclipse IDE Java Oracle
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PrintWriter is closed when you call BufferedWriter.flush(), first run bf.flush(), then pw.close().
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And because your BufferedWriter is wrapped by the PrintWriter, you don't need to call bf.close. It will be done automatically when you call pw.close
Edit: Which is basically what Tomasz said now that I reread it.
 
Marcel Chasiguasin
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joanne Neal wrote:And because your BufferedWriter is wrapped by the PrintWriter, you don't need to call bf.close. It will be done automatically when you call pw.close
Edit: Which is basically what Tomasz said now that I reread it.


Dear Joanne,

for free memory and close the connection. do I only need execute this code
bf.flush();
bf.close();

or this
pw.flush();
pw.close();
???
 
Tomasz Sochanski
Ranch Hand
Posts: 47
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my bet is:

Thanks Joanne for your notice regarding unnecessary call to bf.close().
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcel Chasiguasin wrote:for free memory and close the connection. do I only need execute this code
bf.flush();
bf.close();

or this
pw.flush();
pw.close();
???

You only need to call close on the outermost wrapper object. So, as you have a FileWriter wrapped by a BufferedWriter wrapped by a PrintWriter, calling close on your PrintWriter will also close the FileWriter and BufferedWriter.
I think on most writers calling close will automatically do a flush, but it won't do any harm to call it explicitly.
 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On related note Java 7 has added automatic resource Management which will automatically closed any resource opened inside try block, no need to call close() explicitly.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic