下载中文文件乱码

下载中文名称的文件时,文件会乱码,解决方式使用URLEncoder.encode编码

例:

/**
  * 下载担保书
  * @throws UnsupportedEncodingException
  */
 public void downLoadGurrentBook() throws UnsupportedEncodingException{
  String filePath = "";
  if("agent".equals(downLoadFileName)){
   filePath = ServletActionContext.getServletContext().getRealPath("/jsp/download/代理商担保书.doc");
  }else if("customer".equals(downLoadFileName)){
   filePath = ServletActionContext.getServletContext().getRealPath("/jsp/download/商户情况说明书.doc");
  }
  File file = new File(filePath);
  String fileName = file.getName();
  HttpServletResponse response = getHttpResponse();
  down(file, URLEncoder.encode(fileName,"UTF-8"), response);
 }
    public void down(File f,String filename,HttpServletResponse response)
    {
     response.reset();
     response.setHeader("content-disposition","attachment; filename="+filename); //设置下载的文件名
     long fileLength=f.length();
     String length1=String.valueOf(fileLength);
     response.setHeader("Content_Length",length1); //下载文件的大小
     InputStream in=null;
     OutputStream out = null;
     try{
      in = new FileInputStream( f );
      out = response.getOutputStream();
      byte[] buffer = new byte[2097152];
      int ins = in.read(buffer);//读取字节到buffer中
      //ins == -1 时 。就已经是文件的结尾了
      while ( ins != -1 ) {
       out.write(buffer, 0, ins);//将缓存buffer中的数据写到文件中
       ins = in.read(buffer);
      }
      in.close();
      out.flush();
      out.close();
     }catch (Exception e) {
         System.out.println("--下载发生异常--");
         try {
                    in.close();
                    out.flush();
                    out.close();
                } catch (IOException e1) {
                    System.out.println("--关闭发生异常--");
                    in = null;
                    out = null;
                    e1.printStackTrace();
                }
            }
    }

原文地址:https://www.cnblogs.com/siashan/p/4371918.html