I wrote a simple servlet as follows:
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// [do stuff with the PrintWriter]
out.close();
}
}
Is it necessary to close the PrintWriter
out stream? If I don't close the stream will that affect anything further?
It should be closed after flush() so the PrintWriter object is elligible for garbage collection immediately.
You indeed don't need to do so. Thumb rule: if you didn't create/open it yourself using new SomeOutputStream() , then you don't need to close it yourself. If it was for example a new FileOutputStream("c:/foo. txt") , then you obviously need to close it yourself.
When you call close() the Buffer flushes into the file. You can also call flush() for forcing the data to be written without closing the stream.
If it's not you that's opening the stream, you should not close it.
The stream is opened by the container so the responsibility for closing lies with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With