package com.aptech.print;
import java.io.ByteArrayOutputStream;
import
java.io.PrintStream;
public class Test {
/**
*
獲取Exception的堆棧新息。用于顯示出錯來源時使用。
* @param e
* Exception對象
* @param length
* 需要的信息長度,如果
<=0,表示全部信息
* @return String 返回該Exception的堆棧新息
* @author
李贊紅
*/
public static String getErrorStack(Exception e, int length)
{
String error = null;
if (e != null) {
try
{
ByteArrayOutputStream baos = new
ByteArrayOutputStream();
PrintStream ps = new
PrintStream(baos);
e.printStackTrace(ps);
error =
baos.toString();
if (length > 0) {
if (length >
error.length()) {
length = error.length();
}
error =
error.substring(0,
length);
}
baos.close();
ps.close();
} catch
(Exception e1) {
error = e.toString();
}
}
/*
*
try{ String str=new String(error.getBytes("ISO-8859-1"),"GBK");
* return
str; }catch(Exception e1) { e1.printStackTrace(); }
*/
return
error;
}
public static void main(String[] args) {
try {
Integer.parseInt("中華人民共和國");
} catch (NumberFormatException e) {
String s = Test.getErrorStack(e, 0);
System.out.println("異常信息:" +
s);
}
}
}