在程序中用一个对象(the Decorators)包装另外的一个对象,这是一种被称为Decorator的设计模式
如果要设计自己的IO包装类,这个类需要继承以FilterXXX命名的类,例如,设计一对输入输出包装类:RecordInputStream和RecordOutputStream,来完成从数据库文件中读取记录和往数据库文件中写入记录。
Exception类从Throwable类继承的三个printStackTrace方法的定义如下:
public void printStackTrace()
public void printStackTrace(PrintStream s)
public void printStackTrace(PrintWriter s)
如何把printStackTrace方法打出的详细异常信息存储到一个字符串中?
import java.io.*;
public class TestPrintWriter {
public static void main(String[] args) {
// TODO: Add your code here
try{
throw new Exception("test");
}catch(Exception e){
StringWriter sw=new StringWriter(); //字符串与输出流之间的桥梁StringWriter
PrintWriter pw=new PrintWriter(sw);
e.printStackTrace(pw);
System.out.println(sw.toString());
try{
FileWriter fw=new FileWriter("test.txt");
fw.write(sw.toString()+"中文字符");
fw.close();
}catch(Exception e1){
e1.printStackTrace();
}
}
}
}
本文介绍了一种利用PrintWriter将Exception类的printStackTrace方法输出的异常信息存储为字符串的方法,并演示了如何将该字符串进一步写入文件的过程。
168

被折叠的 条评论
为什么被折叠?



