年底了,感觉应该更新下博客好过年能更愉快的咸鱼一波,哈哈~
感觉最近闲得慌,但是又没有什么好的文章可以分享给大家的,这里我就拿之前困恼过我的一个问题来讲一下吧~
老规矩,先贴上代码,我们再慢慢侃大山~
/**
* 得到完整堆栈异常信息
* @param cause
* @return
*/
public static String stackTraceToString(Throwable cause) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream pout = new PrintStream(out);
cause.printStackTrace(pout);
pout.flush();
try {
return new String(out.toByteArray());
} finally {
try {
out.close();
} catch (IOException ignore) {
// ignore as should never happen
}
}
}
为了使我们的代码更有说服力,我们贴上大名鼎鼎的Netty的源码来看下人家是怎么处理的,作为一款成熟的,功能强大到可以和c语言效率相睥睨,能够处理TCP、UDP、FTP、SMTP等连接的框架,代码一定是非常优雅的。
有人可能就会问了,这不就是骗人嘛,这两个明明就是一个东西,好吧,确实是一样的,取长补短说的就是博主,之前的写法是这样的:
/**
* 得到完整堆栈异常信息
*
* @param throwable
* @return
*/
public static String getStackTrace(Throwable throwable) {
//在try()中的流会被自动调用close方法,此处利用了jdk7的特性
try (Writer result = new StringWriter();
PrintWriter printWriter = new PrintWriter(result)) {
//将堆栈信息写到流中
throwable.printStackTrace(printWriter);
//返回结果
return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
但总的来说,两段代码的意思是差不多的,哈哈