开发者

How to extract content that is sent to a PrintStream?

Im using a thirdparty class that has the following method:

public void print(PrintStream s);

But what I wa开发者_如何学运维nt to do is acually log the output. SOmething like:

RecordingPrintStream p = new RecordingPrintStream
instance.print(p);
logger.log(p.getContents());

So what can I use as my RecordingPrintStream?


Something like:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream recordingStream = new PrintStream(baos);
instance.print(recordingStream);
logger.log(baos.toString());


You can use following contructor to create PrintStream : PrintStream(OutputStream out)

You can use any of StringOutputStream while Creating Printstream object, And get contents from StringBuffer to output with your log method.

class StringOutputStream extends OutputStream {

  StringBuilder mBuf;

  public void write(int byte) throws IOException {
    mBuf.append((char) byte);
  }

  public String getString() {
    return mBuf.toString();
  }
}

So if you want to output to file you use object of FileOutputStream while constructing PrintStream object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜