how to clear contents of a PrintWriter after writing

15,696

Solution 1

Create an in-memory PrintWriter using a StringWriter. You can get the underlying buffer from the StringWriter and clear it if you need to.

StringWriter sr = new StringWriter();
PrintWriter w = new PrintWriter(sr);

w.print("Some stuff");
// Flush writer to ensure that it's not buffering anything
w.flush();
// clear stringwriter
sr.getBuffer().setLength(0);

w.print("New stuff");

// write to Servlet out
w.flush();
response.getWriter().print(sr.toString());

Solution 2

HttpServlteResponse.resetBuffer() will clear the buffered content. But yes, if the response is already flushed to the client it will throw IllegalStateException. Because it is illegal to clear after partial response is sent to the client.

resetBuffer........

void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code. If the response has been committed, this method throws an IllegalStateException.

References:

Cause of Servlet's 'Response Already Committed'

Share:
15,696
Eslam Hamdy
Author by

Eslam Hamdy

Senior engineer with +9 years experience in java ecosystem, have one plus year experience in crafting and managing agile teams, has a passion for nature, mountain biking, swimming, traveling, tensegrity and coding.

Updated on July 19, 2022

Comments

  • Eslam Hamdy
    Eslam Hamdy almost 2 years

    Good evening, i want to know how to clear the data written to a PrintWriter, i.e. is it possible to remove the data from a PrintWriter after printing?

    here in this servlet i print some text to the response and at the line denoted by # i want to remove all the previously printed data and print new stuff:

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String uName = request.getParameter("uName");
        String uPassword = request.getParameter("uPassword");
    
        if (uName .equals("Islam")) {
            out.println("Valid-Name");
            if (uPassword !=null) {
                if (uPassword .equals("Islam")) {
                    // # clear the writer from any printed data here
                    out.println("Valid-password");
                } else {
                    out.println("");
                    out.println("InValid-password");
                }
            }
        } else {
            out.println("InValid-Name");
    
        }
    
    }
    

    Note: i tried out.flush() but the old printed text remains

    • zz3599
      zz3599 about 11 years
      flush should do the trick, followed by close.
    • Ramesh PVK
      Ramesh PVK about 11 years
      Servlet's spec provides a way to do this. Please see the answer below
  • Costi Ciudatu
    Costi Ciudatu about 11 years
    On the second generic approach (response wrapper), or for how to use a StringBuilder ?
  • Eslam Hamdy
    Eslam Hamdy about 11 years
    On the second generic approach (response wrapper)
  • Ramesh PVK
    Ramesh PVK about 11 years
    Servlet's spec provides a way to do this. Please see the answer below.
  • Charles Forsythe
    Charles Forsythe about 11 years
    That method doesn't always work. There is no standard way to guarantee the size of the buffer underlying the Servlet PrintWriter; in fact, it has no obligation to provide one. This method always works.
  • Ramesh PVK
    Ramesh PVK about 11 years
    It will work always provided one knows what Servlet specs says.
  • Charles Forsythe
    Charles Forsythe about 11 years
    The Servlet spec says the the response can be committed when you overflow the buffer in the PrintWriter. You don't know what the buffer size is, and it couldn't, in fact, be 0 bytes. How does that help you make this "always work"?
  • Ramesh PVK
    Ramesh PVK about 11 years
    You can always set your required buffer size. Even if you use your own PrintWriter, you can buffer only to some extent. What cant you set that to Response buffer size.
  • Charles Forsythe
    Charles Forsythe about 11 years
    Oops. You're right. You can both set and query the buffer size. However, if you buffer using a StringWriter, your buffer is limited only by the heap size. If you set the buffer size, you must check to make sure that you are not overwriting it, which requires keeping an accurate count of bytes written. This is complicated because the bytes you write may not match the number of characters you write. The only way for this to be simple is if you make the buffer so large that you never overflow it, which puts unnecessary strain on memory resources.