Spring写入UTF-8响应编码问题

时间:2014-12-18 06:11:24

标签: java spring encoding utf-8

我正在尝试使用Spring 4将Word doc(作为XML)写入响应
我将setContentType设置为utf-8响应,
源xml以UTF-8编码
但是有些UTF-8字符变得像胡言乱语
我做错了什么?

    @RequestMapping(method = RequestMethod.GET, params="action=downloadDocument" )
 public @ResponseBody void getDocumentForStudent(@RequestParam("student_id")String student_id,
                                            HttpServletResponse response) {     
    try {

        response.setContentType("application/msword;charset=utf-8");  
        response.setHeader("Content-encoding","UTF-8");  
        response.setHeader("Content-disposition", "attachment;filename=Document" + student_id +".doc");  

       // document path here 

       InputStream is = new FileInputStream(document);
       BufferedReader rdr = new BufferedReader(new InputStreamReader(is));
       String buf = null;

       PrintWriter output = response.getWriter();
        Set<String> keySet = replaceTokens.keySet();
        while ((buf = rdr.readLine()) != null) {
            for (String key : keySet) {                 
                buf  = buf.replace(key, tokens.get(key));
            }

           output.print(buf);
        }

       response.flushBuffer();
       rdr.close();
        } catch (IOException ex) {
         logger.error("Error writing file to output stream. ", ex);
         throw new RuntimeException("IO Error reading or writing file to output stream!",ex);
     }
 }

1 个答案:

答案 0 :(得分:1)

你可以试试下面的

out.write(buf.getBytes("UTF-8"));  or   out.write(new String(buf, "UTF-8"));

并在阅读文件时也会改变 -

((new FileInputStream(file), "UTF8"));

希望这有助于你