简体   繁体   English

如何将 PrintWriter 转换为 String 或写入文件?

[英]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.我正在使用 JSP 生成动态页面,我想将此动态生成的完整页面保存在文件中作为存档。

In JSP, everything is written to PrintWriter out = response.getWriter();在 JSP 中,一切都写入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 ?如何保存Printwriter内容或转换为String

To get a string from the output of a PrintWriter , you can pass a StringWriter to a PrintWriter via the constructor:要从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);
}

Why not use StringWriter instead?为什么不改用StringWriter 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);

It will depend on: how the PrintWriter is constructed and then used.这将取决于: PrintWriter 是如何构造和使用的。

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 是第一次构造然后传递给写入它的代码,您可以使用装饰器模式,该模式允许您创建 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();
   }
}

You cannot get it with just your PrintWriter object.仅使用PrintWriter对象无法获得它。 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,这不是您应该查看以获取整个字符串的对象,

Along similar lines to what cdc is doing - you can extend PrintWriter and then create and pass around an instance of this new class.与 cdc 所做的类似——您可以扩展PrintWriter ,然后创建并传递这个新类的实例。

Call getArchive() to get a copy of the data that's passed through the writer.调用getArchive()以获取通过getArchive()传递的数据的副本。

public class ArchiveWriter extends PrintWriter {
    private StringBuilder data = new StringBuilder();

    public ArchiveWriter(Writer out) {
        super(out);
    }

    public ArchiveWriter(Writer out, boolean autoFlush) {
        super(out, autoFlush);
    }

    public ArchiveWriter(OutputStream out) {
        super(out);
    }

    public ArchiveWriter(OutputStream out, boolean autoFlush) {
        super(out, autoFlush);
    }

    public ArchiveWriter(String fileName) throws FileNotFoundException {
        super(fileName);
    }

    public ArchiveWriter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException {
        super(fileName, csn);
    }

    public ArchiveWriter(File file) throws FileNotFoundException {
        super(file);
    }

    public ArchiveWriter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException {
        super(file, csn);
    }

    @Override
    public void write(char[] cbuf, int off, int len) {
        super.write(cbuf, off,len);
        data.append(cbuf, off, len);
    }

    @Override
    public void write(String s, int off, int len) {
        super.write(s, off,len);
        data.append(s, off, len);
    }

    public String getArchive() {
        return data.toString();
    }
}

我认为最好的方法是在 StringBuffer 等其他对象中准备您的响应,并将其内容推送到响应中,然后将存储在该变量中的内容保存到文件中。

This helped me: for obtaining a SOAP-able object as XML string.这对我有帮助:用于获取 SOAP-able 对象作为 XML 字符串。

JAXBContext jc = JAXBContext.newInstance(o.getClass());
Marshaller m = jc.createMarshaller();
StringWriter writer = new StringWriter();
m.marshal( o, new PrintWriter(writer) );
return writer.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM