Convert Stream to String

JavaMail debug info is sent by default to System.out

I want to direct it to a log4j logger instead so I need to get each line of log data as a String that I can use in the Log methods.

I can see on the JavaMail Session class that I can set the Stream that the debug info is written to using:

public void setDebugOut(java.io.PrintStream out)

What I'm unsure about is how to create a PrintStream from which I can capture each line of debug data as a String.

Any help would be appreciated.

[524 byte] By [miciuli] at [2007-9-30 20:27:30]
# 1

The "string" representation of a stream can only be determined when the stream is closed - ie, when the streaming has finished. I dbout this will happen in your case!

Another alternative is to decide that you generate Strings whenever the stream is flushed or a new line character is received.

You may be best off extending ByteArrayOutputStream so that its flush/close methods send the current contents to Log4J then reset the buffer:

public void flush()

{

logger.debug(toString());

reset();

}

etc.

You should then be able to wrap this up in a PrintStream (setting autoflush to true).

Not ideal as it may generate more log entries than debug events but probably good enough for debug.

Hope this helps.

KPSeal at 2007-7-7 1:11:53 > top of Java-index,Java Essentials,Java Programming...
# 2
Cheers KP - that's pretty much the way I went.Decided to set auto flush false and watch for line end characters myself in the end though.
miciuli at 2007-7-7 1:11:53 > top of Java-index,Java Essentials,Java Programming...
# 3
Fair enough - glad your problem's sorted out. Thanks for the DDs!
KPSeal at 2007-7-7 1:11:53 > top of Java-index,Java Essentials,Java Programming...