StringWriter/PrintWriter在Java输出异常信息中的作用
閑來無事,看看JUnit的源代碼。剛剛開始看就發現一段有趣的代碼:
public String trace() {StringWriter stringWriter = new StringWriter();PrintWriter writer = new PrintWriter(stringWriter);thrownException().printStackTrace(writer);StringBuffer buffer = stringWriter.getBuffer();return buffer.toString();}此前我并未接觸過StringWriter和PrintWriter。對此感到好奇。其實Java的IO是比較復雜的,因為很多類提供的接口需要的IO參數類型是固定的,而我們掌握的數據或者說需要輸入的數據卻是很多封裝類型的,故此經常需要做封裝工作。(個人的小體會而已,我對IO一塊沒有太多經驗)
查閱Java API文檔,發現了:
void printStackTrace() Prints this throwable and its backtrace to the standard error stream.void printStackTrace(PrintStream s) Prints this throwable and its backtrace to the specified print stream. void printStackTrace(PrintWriter s) Prints this throwable and its backtrace to the specified print writer.從上面的信息可以看出,Throwable(Exception繼承的一個基類)的錯誤輸入有三種,printStackTrace()是指將異常本身和異常信息輸出到標準的錯誤流;printStatckTrace(PrintStream s)是指將異常本身和異常信息輸出到PrintStream的對象中;第三種則是輸出到PrintWriter中。
在普通的情況中,如果我們用IDE的話,錯誤一般是直接輸出到Console中,但是有時候我們需要將異常信息輸出到文件中、或者是其他網頁中,這時候就需要使用帶參數的兩個API接口。
此處使用PrintWriter,PrintWriter的構造函數比較多種,我使用StringWriter作為構造參數。
為了證實可行性。寫一個小程序跑一下。
import java.io.PrintWriter; import java.io.StringWriter;@SuppressWarnings("serial") public class MyException extends Exception{ public String getPrintStackTraceAsString(){ StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); printStackTrace(pw);//將異常信息輸入到pw(PrintWriter)中 StringBuffer sb = sw.getBuffer(); return sb.toString(); } } public class TestException { public static void main(String[] args) { try { throw new MyException(); } catch (MyException e) { // 由于實現的方法定義在MyException中,所以catch的參數不可以向上轉型為Exception System.out.println("I am not an average Exception: " + e.getPrintStackTraceAsString()); // e.printStackTrace(); } } }當使用e.printStackTrace()方法時,得到以下結果:
MyException?
at TestException.main(TestException.java:4)?
?
而使用我們定義的方法時:
I am not an average Exception: MyException?
at TestException.main(TestException.java:4)?
此外:
1)Throwable本身也有getStackTrace()方法。
2)關于PrintWriter和PrintStream的區別,可以參考:http://hi.baidu.com/shdren09/item/8b1d2631e78b7abf623aff3f ?
轉載于:https://www.cnblogs.com/Evil-Rebe/p/4869389.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的StringWriter/PrintWriter在Java输出异常信息中的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法录 之 复杂度分析。
- 下一篇: lintcode:Singleton 单