Copy codeThe Code is as follows: public static String toUtf8String (String s ){
StringBuffer sb = new StringBuffer ();
For (int I = 0; I <s. length (); I ++ ){
Char c = s. charAt (I );
If (c> = 0 & c <= 255 ){
Sb. append (c );
} Else {
Byte [] B;
Try {
B = Character. toString (c). getBytes ("UTF-8 ");
} Catch (Exception ex ){
Predictionutil. error ("an error occurred when converting Chinese characters in the file name into UTF-8 encoded strings. The input string is:" + s );
B = new byte [0];
}
For (int j = 0; j <B. length; j ++ ){
Int k = B [j];
If (k <0)
K + = 256;
Sb. append ("%" + Integer. toHexString (k). toUpperCase ());
}
}
}
Return sb. toString ();
}
/**
* Convert Chinese characters in the file name into UTF-8 encoded strings based on different browsers, so that the file name can be correctly displayed during download.
*
* @ Param s
* Original file name
* @ Return the reencoded file name
*/
Public static String toUtf8String (HttpServletRequest request, String s ){
String agent = request. getHeader ("User-Agent ");
Try {
Boolean isFireFox = (agent! = Null & agent. toLowerCase (). indexOf ("firefox ")! =-1 );
If (isFireFox ){
S = new String (s. getBytes ("UTF-8"), "ISO8859-1 ");
} Else {
S = StringUtil. toUtf8String (s );
If (agent! = Null & agent. indexOf ("MSIE ")! =-1 )){
// See http://support.microsoft.com/default.aspx? Kbid = 816868
If (s. length () & gt; 150 ){
// Obtain the possible Encoding Based on the locale of the request
S = new String (s. getBytes ("UTF-8"), "ISO8859-1 ");
}
}
}
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
}
Return s;
}