Java下载文件时文件名中的中文变成下划线,其他正常

  1. 问题:
    Java下载文件时文件名中的中文变成下划线,其他正常
  2. 问题源码
package com.lm.cms2.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class LogController {
    @RequestMapping("/downloadlog")
    public HttpServletResponse download( HttpServletResponse response,String path) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8")));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }
    
}

  1. 解决办法
    31行代码后面多家一个编码ISO8859-1
 response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));

正常显示
Java下载文件时文件名中的中文变成下划线,其他正常
OJBK
4. 拓展一下

String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组
String.getBytes(String decode1)方法会根据指定的decode编码返回某字符串在该编码下的byte数组
new String(byte[],decode2)方法是 使用decode2编码来还原byte数组