java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 下载文件时文件名乱码

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

作者:

我最近在开发时遇到了文件另存为时文件名出现乱码,在火狐上正常的文件名,在IE中又出现乱码问题,然后好不容易在IE下调试好了文件名乱码问题,在火狐下又出现乱码,最后终于感觉这样是能解决了。具体如下:
复制代码 代码如下:

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;
         }
您可能感兴趣的文章:
阅读全文