欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-13 13:42:10
复制代码 代码如下:public static string toutf8string(string s) {      ...
复制代码 代码如下:

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;
         }

上一篇:

下一篇: