首页 > 编程 > Java > 正文

Java下载文件时文件名乱码问题解决办法

2019-11-26 16:11:35
字体:
来源:转载
供稿:网友
复制代码 代码如下:

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) {
                         exceptionUtil.error("将文件名中的汉字转为UTF8编码的串时错误,输入的字符串为:" + 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();
         }

         /**
          * 根据不同浏览器将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
          * 
          * @param s
          *            原文件名
          * @return 重新编码后的文件名
          */
         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) {
                             // 根据request的locale 得出可能的编码
                             s = new String(s.getBytes("UTF-8"), "ISO8859-1");
                         }
                     }
                 }
             } catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
             }
             return s;
         }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表