File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Regarding closing the writers in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding closing the writers in java" Watch "Regarding closing the writers in java" New topic
Author

Regarding closing the writers in java

praveen oruganti
Ranch Hand

Joined: Feb 05, 2007
Posts: 73
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.


Regards,<br />Praveen Oruganti<br />Software Programmer
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
praveen oruganti
Ranch Hand

Joined: Feb 05, 2007
Posts: 73
Whether it is necessary to introduce the flush for the writer before closing it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36464
    
  15
Look at the API for flush and close; that should answer your question.
praveen oruganti
Ranch Hand

Joined: Feb 05, 2007
Posts: 73
Yes i got it, Whenever we close the writer it will automatically calls the flush first.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36464
    
  15
Originally posted by praveen oruganti:
Yes i got it . . .


 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding closing the writers in java
 
Similar Threads
Tracking Stack Trace Information
storing stack trace into string
ex.printStackTrace() to String
java.lang.IllegalStateException
Find Calling Class' name within Called Class