Issue
StringWriter sWriter = new StringWriter();
PrintWriter out = new PrintWriter(sWriter);
out.println("Hello World");
response.getWriter().print(sWriter.toString());
OR
Printwriter out = response.getWriter();
- What is difference between these two while we use them in Java Servlet
- Which one is efficient in Servlet
Solution
StringWriter sWriter = new StringWriter();
PrintWriter out = new PrintWriter(sWriter);
out.println("Hello World");
response.getWriter().print(sWriter.toString());
This creates a StringWriter
that is independent of the response. It creates a String
with the content you put in it and then takes that and puts it into PrintWriter
of the response.
PrintWriter out = response.getWriter();
This just gets the PrintWriter
that writes to the response.
If you write to that, it is directly given to the response.
The second method is more efficient because java doesn't have to create a single String with your whole content but can directly deliver it.
Answered By - dan1st
Answer Checked By - Timothy Miller (JavaFixing Admin)