This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding closing the writers in java

 
praveen oruganti
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am having a small doubt rgarding closing of writers in java.

I have written a method called getStackTrace in my program.

public static String getStackTrace(Throwable aThrowable) {
final StringWriter result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
Whether i need to close the StringWriter and PrintWriter compulsory due to unclosing of writers whether it causes any memory leak due to temporary unused java objects.

Please guide me in this regard.
 
Rob Spoor
Sheriff
Pie
Posts: 20529
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While for some readers / writers / streams it's not necessary to explicitly close them (StringWriter and ByteArrayInputStream / -OutputStream being amonth them since these have only Java resources - no file handles or anything similar), it's always a good idea to close them anyways:

Also, always close the wrapping objects, not the wrapped. These wrapping objects may need to send some finalizing data, e.g. ZipOutputStream. I once had a problem where I closed its underlying stream instead, and the ZIP files were corrupted.
 
praveen oruganti
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whether it is necessary to introduce the flush for the writer before closing it.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48957
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at the API for flush and close; that should answer your question.
 
praveen oruganti
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes i got it, Whenever we close the writer it will automatically calls the flush first.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48957
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by praveen oruganti:
Yes i got it . . .


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic