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);
} それ以外 {
バイト[] b;
試す {
b = Character.toString(c).getBytes("utf-8");
} catch (例外例) {
ExceptionUtil.error("ファイル名の中国語文字を UTF8 エンコード文字列に変換するときにエラーが発生しました。入力文字列は次のとおりです: " + s);
b = 新しいバイト[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
sb.toString() を返します。
}
/**
※ダウンロード時に保存ファイル名が正しく表示されるよう、ブラウザごとにファイル名の漢字をUTF8エンコード文字列に変換してください。
*
* @param
※元のファイル名
* @return 再エンコードされたファイル名
*/
public static String toUtf8String(HttpServletRequest request, String s) {
文字列エージェント = request.getHeader("ユーザーエージェント");
試す {
boolean isFireFox = (エージェント != null && Agent.toLowerCase().indexOf("firefox") != -1);
if (isFireFox) {
s = 新しい String(s.getBytes("UTF-8"), "ISO8859-1");
} それ以外 {
s = StringUtil.toUtf8String(s);
if ((エージェント != null && エージェント.indexOf("MSIE") != -1)) {
// http://support.microsoft.com/default.aspx?kbid=816868 を参照してください。
if (s.length() > 150) {
// リクエストのロケールに基づいて可能なエンコーディングを取得します
s = 新しい String(s.getBytes("UTF-8"), "ISO8859-1");
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
を返します。
}