StringWriter/PrintWriter在Java输出异常信息中的作用
閑來(lái)無(wú)事,看看JUnit的源代碼。剛剛開(kāi)始看就發(fā)現(xiàn)一段有趣的代碼:
public String trace() {StringWriter stringWriter = new StringWriter();PrintWriter writer = new PrintWriter(stringWriter);thrownException().printStackTrace(writer);StringBuffer buffer = stringWriter.getBuffer();return buffer.toString();}此前我并未接觸過(guò)StringWriter和PrintWriter。對(duì)此感到好奇。其實(shí)Java的IO是比較復(fù)雜的,因?yàn)楹芏囝愄峁┑慕涌谛枰腎O參數(shù)類型是固定的,而我們掌握的數(shù)據(jù)或者說(shuō)需要輸入的數(shù)據(jù)卻是很多封裝類型的,故此經(jīng)常需要做封裝工作。(個(gè)人的小體會(huì)而已,我對(duì)IO一塊沒(méi)有太多經(jīng)驗(yàn))
查閱Java API文檔,發(fā)現(xiàn)了:
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繼承的一個(gè)基類)的錯(cuò)誤輸入有三種,printStackTrace()是指將異常本身和異常信息輸出到標(biāo)準(zhǔn)的錯(cuò)誤流;printStatckTrace(PrintStream s)是指將異常本身和異常信息輸出到PrintStream的對(duì)象中;第三種則是輸出到PrintWriter中。
在普通的情況中,如果我們用IDE的話,錯(cuò)誤一般是直接輸出到Console中,但是有時(shí)候我們需要將異常信息輸出到文件中、或者是其他網(wǎng)頁(yè)中,這時(shí)候就需要使用帶參數(shù)的兩個(gè)API接口。
此處使用PrintWriter,PrintWriter的構(gòu)造函數(shù)比較多種,我使用StringWriter作為構(gòu)造參數(shù)。
為了證實(shí)可行性。寫(xiě)一個(gè)小程序跑一下。
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) { // 由于實(shí)現(xiàn)的方法定義在MyException中,所以catch的參數(shù)不可以向上轉(zhuǎn)型為Exception System.out.println("I am not an average Exception: " + e.getPrintStackTraceAsString()); // e.printStackTrace(); } } }當(dāng)使用e.printStackTrace()方法時(shí),得到以下結(jié)果:
MyException?
at TestException.main(TestException.java:4)?
?
而使用我們定義的方法時(shí):
I am not an average Exception: MyException?
at TestException.main(TestException.java:4)?
此外:
1)Throwable本身也有g(shù)etStackTrace()方法。
2)關(guān)于PrintWriter和PrintStream的區(qū)別,可以參考:http://hi.baidu.com/shdren09/item/8b1d2631e78b7abf623aff3f ?
轉(zhuǎn)載于:https://www.cnblogs.com/Evil-Rebe/p/4869389.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的StringWriter/PrintWriter在Java输出异常信息中的作用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 算法录 之 复杂度分析。
- 下一篇: java美元兑换,(Java实现) 美元