开发者

java: StringBufferOutputWriter or StringBufferOutputStream?

开发者 https://www.devze.com 2022-12-11 22:39 出处:网络
I need to take a caught exception and get a String that is what would be printed using printStackTrace().

I need to take a caught exception and get a String that is what would be printed using printStackTrace().

It looks like the simplest thing is to call printStackTrace(X), where X subclasses a PrintStream or PrintWriter, and gathers it to a StringBuilder and can return a String.

Does such a thing exist? If not, any suggestions how to do this?

edit: skaffman posted 开发者_开发百科a solution that used getStackTrace(). (can you or moderators undelete?) This is actually the only solution that works "right". The problem with using PrintWriter on top of StringWriter, although it works easily, is that for deep stack traces it doesn't print all the elements.


What you want is StringWriter

You can pass that into the constructor of a PrintWriter and then call getBuffer() on to the StringWriter or toString() to get the final string.


How about, instead of printStackTrace, you call Throwable.getStackTrace(), which returns StackTraceElement[]? You still need to do some work to get it into a String, but it's arguably a cleaner solution than hacking about with string buffers and the like.

Once you have the StackTraceElement[], you can manipulate that. It may be that the layout as dictated by printStackTrace isn't really suitable for what you're going to use it for, and that more explicit formatting as provided by the StackTraceElement object model gives you more control. That is what it was provided for, after all.


Guava contains this in its com.google.common.base.Throwables class:

public static String getStackTraceAsString(Throwable throwable) {
  StringWriter sw = new StringWriter();
  throwable.printStackTrace(new PrintWriter(sw));
  return sw.toString();
}
0

精彩评论

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

关注公众号