写入后如何清除PrintWriter的内容

编程入门 行业动态 更新时间:2024-10-24 16:27:11
本文介绍了写入后如何清除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的内容

本文发布于:2023-11-03 16:28:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内容   PrintWriter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!