如何将 PrintWriter 转换为字符串或写入文件?
我正在使用 JSP 生成动态页面,我想将此动态生成的完整页面保存在文件中作为存档。
在 JSP 中,所有内容都写入 PrintWriter out = response.getWriter();
在页面末尾,在向客户端发送响应之前,我想将此页面保存在文件中或作为字符串保存在缓冲区中后期治疗。
如何保存 Printwriter
内容或转换为 String
?
I am generating dynamic page using JSP, I want to save this dynamically generated complete page in file as archive.
In JSP, everything is written to PrintWriter out = response.getWriter();
At the end of page, before sending response to client I want to save this page, either in file or in buffer as string for later treatment.
How can I save Printwriter
content or convert to String
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
要从
PrintWriter
的输出中获取字符串,您可以通过构造函数将StringWriter
传递给PrintWriter
:To get a string from the output of a
PrintWriter
, you can pass aStringWriter
to aPrintWriter
via the constructor:为什么不使用
StringWriter
代替?我想这应该能够提供你所需要的。例如:
Why not use
StringWriter
instead? I think this should be able to provide what you need.So for example:
这将取决于: PrintWriter 的构造和使用方式。
如果首先构造 PrintWriter,然后将其传递给写入它的代码,则可以使用装饰器模式,该模式允许您创建 Writer 的子类,该子类将 PrintWriter 作为委托,并将调用转发给委托,但是还维护内容的副本,您可以将其存档。
It will depend on: how the PrintWriter is constructed and then used.
If the PrintWriter is constructed 1st and then passed to code that writes to it, you could use the Decorator pattern that allows you to create a sub-class of Writer, that takes the PrintWriter as a delegate, and forwards calls to the delegate, but also maintains a copy of the content that you can then archive.
您无法仅使用
PrintWriter
对象来获取它。它刷新数据,并且其内部不保存任何内容。这不是您应该查看以获取整个字符串的对象,You cannot get it with just your
PrintWriter
object. It flushes the data, and does not hold any content within itself. This isn't the object you should be looking at to get the entire string,我认为最好的方法是在 StringBuffer 等其他对象中准备响应,并将其内容推送到响应中,然后将存储在该变量中的内容保存到文件中。
The best way I think is prepare your response in other object like StringBuffer, and fush its content to the response, and after save the content stored in that variable to the file.
这对我有帮助:以 XML 字符串的形式获取支持 SOAP 的对象。
This helped me: for obtaining a SOAP-able object as XML string.
与 cdc 所做的类似 - 您可以扩展 PrintWriter,然后创建并传递这个新类的实例。
调用 getArchive() 来获取通过编写器传递的数据的副本。
Along similar lines to what cdc is doing - you can extend
PrintWriter
and then create and pass around an instance of this new class.Call
getArchive()
to get a copy of the data that's passed through the writer.