Closure of streams in Java

1.response.getWriter().print("");

2.PrintWriter out = response.getWriter();
  out.print("");
  out.close();

is the first way all right? Will the stream close automatically?

Mar.09,2021

when using HttpServletResponse.getOutputStream () /. GetWriter (), leaving it off is a better choice.
reason:

    The
  1. container always closes for you at the end of the Servlet life cycle;
  2. if there is chained processing later (for example, if Filter), is turned off, response will not be available;
  3. write less code and less bug.

response.getWriter (). Print (""); does not close automatically

response.getWriter
public PrintWriter getWriter()
/*     */     throws IOException
/*     */   {
/* 213 */     PrintWriter writer = this.response.getWriter();
/* 214 */     if (isFinished()) {
/* 215 */       this.response.setSuspended(true);
/*     */     }
/* 217 */     return writer;
/*     */   }
print
public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }
    
Menu