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) {
exceptionUtil.error("Error when converting Chinese characters in the file name to UTF8 encoded string, 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 the Chinese characters in the file name to a UTF8-encoded string according to different browsers, so that the saved file name can be displayed correctly when downloading.
*
* @param s
*Original file name
* @return the re-encoded 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() > 150) {
// Get 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;
}