Forums Register Login

Regarding closing the writers in java

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Whether it is necessary to introduce the flush for the writer before closing it.
+Pie Number of slices to send: Send
Look at the API for flush and close; that should answer your question.
+Pie Number of slices to send: Send
Yes i got it, Whenever we close the writer it will automatically calls the flush first.
+Pie Number of slices to send: Send
 

Originally posted by praveen oruganti:
Yes i got it . . .



If you look closely at this tiny ad, you will see five bicycles and a naked woman:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 3165 times.
Similar Threads
storing stack trace into string
java.lang.IllegalStateException
Find Calling Class' name within Called Class
ex.printStackTrace() to String
Tracking Stack Trace Information
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 01:25:12.