本文介绍了写入后如何清除PrintWriter的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

晚上好,我想知道如何清除写入到PrintWriter中的数据,即,打印后是否可以从PrintWriter中删除数据?

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?

在此servlet中,我在响应中打印一些文本,并在#表示的行上删除所有先前打印的数据并打印新内容:

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");

    }

}

注意:我尝试过out.flush(),但旧的打印文本仍然保留

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

推荐答案

使用 StringWriter 创建内存中的 PrintWriter .您可以从 StringWriter 获取基础缓冲区,并在需要时清除它.

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());

这篇关于写入后如何清除PrintWriter的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 09:23