superzoom superzoom - 6 months ago 80
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
Printwriter
content or convert to
String
?

cdc cdc
Answer

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
   {
      this.delegate.flush();
      this.archive.flush();

   } 

   public void close() throws IOException
   {
      this.delegate.close();
      this.archive.close();
   }
}