写入后如何清除PrintWriter的内容
晚上好,我想知道如何清除写入到PrintWriter的数据,即是否可以在打印后从PrintWriter删除数据?
在此servlet中,我在响应中打印一些文本,并在#表示的行上希望删除所有先前打印的数据并打印新内容:
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(),但旧的打印文本仍然保留
回答:
创建一个内存PrintWriter
使用StringWriter
。您可以从获取底层缓冲区,StringWriter
并在需要时清除它。
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的内容 的全部内容, 来源链接: utcz.com/qa/420336.html