我想将异常的堆栈信息保存到数据库中作为日志方便以后查看,在数据库中堆栈信息用字节数组保存.在程序中我是这样调的catch (Exception e) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(b);
e.printStackTrace(pw);
pw.close();
// 调用b.toByteArray转换成字节数组保存到数据库中
}
但是这里就有一个疑问,从字节数组转换到字符串是需要指定字符编码集的,但是我不知道保存的时候编码集是什么.做了下面的试验:System.out.println(new String(b)); // b是从异常中读出的字节数组 发现可以打印出正常的信息,中文也没有乱码.那我的推论是保存时是按照机器的默认字符集保存的,所以使用new String(byte b)构造字符串时也没有问题.但是如果我保存和读取不在同一台机器,而这两台机器又不是一种字符集,那又该怎么办呢?我的想法是能不能在保存的时候就指定好字符集呢?

解决方案 »

  1.   


    你没有指定编码,默认就是按照OS编码(或IDE的设置)存取,所以在本机正常。对于你的问题,建议你在保存的时候指定字符集。
      

  2.   


    在 ByteArrayOutputStream类里边有一个这个方法,可以指定编码   
    [code=Java/**]
         * Converts the buffer's contents into a string, translating bytes into
         * characters according to the specified character encoding.
         *
         * @param   enc  a character-encoding name.
         * @return String translated from the buffer's contents.
         * @throws UnsupportedEncodingException
         *         If the named encoding is not supported.
         * @since   JDK1.1
         */
        public String toString(String enc) throws UnsupportedEncodingException {
    return new String(buf, 0, count, enc);
        }[/code]
      

  3.   

    在 ByteArrayOutputStream类里边有一个这个方法,可以指定编码  
     
        * Converts the buffer's contents into a string, translating bytes into 
        * characters according to the specified character encoding. 
        * 
        * @param  enc  a character-encoding name. 
        * @return String translated from the buffer's contents. 
        * @throws UnsupportedEncodingException 
        *        If the named encoding is not supported. 
        * @since  JDK1.1 
        */ 
        public String toString(String enc) throws UnsupportedEncodingException { 
    return new String(buf, 0, count, enc); 
        }  
      

  4.   

    为什么不用log4j哦,还要自己写,这样的效率很低,如果请求很多,会宕机的
      

  5.   

    找到了,在PrintWriter的构造函数中:
    public PrintWriter(OutputStream out)
    根据现有的 OutputStream 创建不带自动行刷新的新 PrintWriter。此便捷构造方法创建必要的中间 OutputStreamWriter,后者使用默认字符编码将字符转换为字节。 所以应该使用public PrintWriter(Writer out)构造.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(baos, MESSAGE_UNCODING);
    PrintWriter pw = new PrintWriter(osw);
    exception.printStackTrace(pw);
    pw.close();
    return baos.toByteArray();