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 ?


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();
   }
}

Why not use StringWriter instead? I think this should be able to provide what you need.

So for example:

StringWriter strOut = new StringWriter();
...
String output = strOut.toString();
System.out.println(output);

要从PrintWriter的输出中获取字符串,可以通过构造函数将StringWriter传递给PrintWriter

@Test
public void writerTest(){
    StringWriter out = new StringWriter();
    PrintWriter writer = new PrintWriter(out);

    // use writer, e.g.:
    writer.print("ABC");
    writer.print("DEF");

    writer.flush(); // flush is really optional here, as Writer calls the empty StringWriter.flush
    String result = out.toString();

    assertEquals("ABCDEF", result);
}
链接地址: http://www.djcxy.com/p/46066.html

上一篇: 使用servlet的jQuery自动完成UI不会返回任何数据

下一篇: 如何将PrintWriter转换为字符串或写入文件?