PackageCom.gootrip.util;Importjava.io.UnsupportedEncodingException;/*** <p>title: Character encoding tool class </p>*/ Public classChartools {/*** Convert code iso-8859-1 to GB2312 *@paramtext *@return */ Public Static Finalstring ISO2GB (String text) {string result= ""; Try{result=NewString (Text.getbytes ("iso-8859-1"), "GB2312"); } Catch(Unsupportedencodingexception ex) {result=ex.tostring (); } returnresult; } /*** Convert code GB2312 to Iso-8859-1 *@paramtext *@return */ Public Static Finalstring Gb2iso (String text) {string result= ""; Try{result=NewString (Text.getbytes ("GB2312"), "Iso-8859-1"); } Catch(Unsupportedencodingexception ex) {ex.printstacktrace (); } returnresult; } /*** Utf8url Code *@paramS *@return */ Public Static Finalstring Utf8urlencode (string text) {StringBuffer result=NewStringBuffer (); for(inti = 0; I < text.length (); i++) { Charc =Text.charat (i); if(c >= 0 && C <= 255) {result.append (c); }Else { byte[] B =New byte[0]; Try{b= Character.tostring (c). GetBytes ("UTF-8"); }Catch(Exception ex) {} for(intj = 0; J < B.length; J + +) { intK =B[j]; if(k < 0) K + = 256; Result.append ("%" +integer.tohexstring (k). toUpperCase ()); } } } returnresult.tostring (); } /*** Utf8url decoding *@paramtext *@return */ Public Static Finalstring Utf8urldecode (String text) {string result= ""; intp = 0; if(text!=NULL&& text.length () >0) {text=text.tolowercase (); P= Text.indexof ("%e"); if(p = =-1)returntext; while(P! =-1) {result+ = text.substring (0, p); Text=text.substring (P, text.length ()); if(Text = = "" | | Text.length () < 9)returnresult; Result+ = Codetoword (text.substring (0, 9)); Text= Text.substring (9, Text.length ()); P= Text.indexof ("%e"); } } returnResult +text; } /*** Utf8url encoded to characters *@paramtext *@return */ Private Static Finalstring Codetoword (String text) {string result; if(Utf8codecheck (text)) {byte[] Code =New byte[3]; code[0] = (byte) (Integer.parseint (text.substring (1, 3), 16)-256); code[1] = (byte) (Integer.parseint (Text.substring (4, 6), 16)-256); code[2] = (byte) (Integer.parseint (Text.substring (7, 9), 16)-256); Try{result=NewString (Code, "UTF-8"); }Catch(Unsupportedencodingexception ex) {result=NULL; } } Else{result=text; } returnresult; } /*** Encoding is valid *@paramtext *@return */ Private Static Final BooleanUtf8codecheck (String text) {string sign= ""; if(Text.startswith ("%e")) for(inti = 0, p = 0; P! =-1; i++) {p= Text.indexof ("%", p); if(P! =-1) P++; Sign+=p; } returnSign.equals ("147-1"); } /*** Determine if utf8url code *@paramtext *@return */ Public Static Final BooleanIsutf8url (String text) {text=text.tolowercase (); intp = text.indexof ("%"); if(P! =-1 && text.length ()-p > 9) {text= Text.substring (p, p + 9); } returnUtf8codecheck (text); } }
JAVA Encoding format Conversion Tool class