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

我正在使用JSP生成动态页面,我想将此动态生成的完整页面保存为文件文件。

在JSP中,所有内容都写入PrintWriter out = response.getWriter();

在页面结尾处,在向客户端发送响应之前,我希望将此页面保存在文件或缓冲区中作为后续处理的字符串。

如何保存Printwriter内容或将其转换为String


它将取决于:PrintWriter是如何构建和使用的。

如果PrintWriter构造为1st,然后传递给写入它的代码,则可以使用Decorator模式,该模式允许您创建Writer的子类,将PrintWriter作为委托,并将调用转发给委托,但还维护您可以归档的内容的副本。

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

为什么不使用StringWriter呢? 我认为这应该能够提供你所需要的。

例如:

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/46065.html

上一篇: how to convert PrintWriter to String or write to a File?

下一篇: displaying database data from java servlet to jsp as json