Java下载中文乱码问题解决方法

问题描述:Java应用下载文件功能,输出文件名中的中文乱码

测试环境:tomcat,websphere6.1

方法一:

response.setContentType("application/x-download");

fileName = URLDecoder.decode(fileName, "utf-8");

fileName= java.net.URLEncoder.encode(fileName,"utf-8");

response.setHeader("Content-Disposition", "attachment; filename=\""+ new String((fileName + ".zip").getBytes(),"UTF-8") +"\"");

 

方法二:

response.setHeader("Content-Disposition", "attachment;filename=" + toUtf8String(filename));

    

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) {

                log.error(ex);

                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();

}

posted @ 2010-12-16 17:47  镜涛  阅读(610)  评论(0编辑  收藏  举报
Creative Commons License

本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名孙镜涛(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言