晚上好,我想知道如何清除写入到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的内容
发布评论