superzoom superzoom - 1 year ago 129
Java Question

how to convert PrintWriter to String or write to a File?

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
content or convert to

cdc cdc
Answer Source

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.

public class DecoratedWriter extends Writer
   private final Writer delegate;

   private final StringWriter archive = new StringWriter();

   //pass in the original PrintWriter here
   public DecoratedWriter( Writer delegate )
      this.delegate = delegate;

   public String getForArchive()
      return this.archive.toString();

   public void write( char[] cbuf, int off, int len ) throws IOException
      this.delegate.write( cbuf, off, len );
      this.archive.write( cbuf, off, len );

   public void flush() throws IOException


   public void close() throws IOException