java判斷獲取到的中文字符串是否亂碼


/**  
         *  用getBytes(encoding):返回字符串的一個byte數組  
         *  當b[0]為  63時,應該是轉碼錯誤  
         *  A、不亂碼的漢字字符串:  
         *  1、encoding用GB2312時,每byte是負數;  
         *  2、encoding用ISO8859_1時,b[i]全是63。  
         *  B、亂碼的漢字字符串:  
         *  1、encoding用ISO8859_1時,每byte也是負數;  
         *  2、encoding用GB2312時,b[i]大部分是63。  
         *  C、英文字符串  
         *  1、encoding用ISO8859_1和GB2312時,每byte都大於0;  
         *  總結:給定一個字符串,用getBytes("iso8859_1")  
         *  1、如果b[i]有63,不用轉碼;  A-2  
         *  2、如果b[i]全大於0,那么為英文字符串,不用轉碼;  B-1  
         *  3、如果b[i]有小於0的,那么已經亂碼,要轉碼。  C-1  
         */ 

 

 private  static  String  toGb2312(String  str)  {  
               if  (str  ==  null)  return  null;  
               String  retStr  =  str;  
               byte  b[];  
               try  {  
                       b  =  str.getBytes("ISO8859_1"); 
                       for  (int  i  =  0;  i  <  b.length;  i++)  {  
                               byte  b1  =  b[i];  
                               if  (b1  ==  63)  
                                       break;    //1  
                               else  if  (b1  >  0)  
                                       continue;//2  
                               else  if  (b1  <  0)  {        //不可能為0,0為字符串結束符 
//小於0亂碼
                                       retStr  =  new  String(b,  "GB2312");  
                                       break;  
                               }  
                       }  
               }  catch  (UnsupportedEncodingException  e)  {  
                       //  e.printStackTrace();   
               }  
               return  retStr;  
       } 

java技術交流群: 57388149

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM