使用HttpServletResponse创建UTF-8文件

时间:2012-02-19 23:19:01

标签: servlets utf-8 character-encoding outputstream

我正在尝试使用HttpServletResponse(HttpServlet)创建一个UTF-8文件“myFile.aaa”。我之所以需要它是UTF-8,是因为它可能包含特殊的不可打印字符。

但是,下面的代码似乎创建了ANSI编码的文件。至少这是Notepad ++所说的,以及从这个文件中读取字符的内容。我做错了什么?

由于

public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    {
        res.setHeader("Content-Type", "application/octet-stream; charset=UTF-8");
        res.setHeader("Content-Disposition","attachment;filename=myFile.aaa");
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream os = res.getOutputStream();
        os.print("Hello World");
        os.flush();
        os.close();
    }

2 个答案:

答案 0 :(得分:11)

您需要使用响应的字符编写器,而不是字节输出流。

替换

ServletOutputStream os = res.getOutputStream();
os.print("Hello World");
os.flush();
os.close();

通过

res.getWriter().write("Some UTF-8");

此外,我建议将内容类型设置为text/plain,而不是过于通用的内容类型,这意味着二进制内容,而不是字符内容。

我不确定Notepad ++,但在记事本中,如果文本文档不包含ANSI范围之外的任何字符,它将被解释为ANSI。不要因为这种行为而误导你。

答案 1 :(得分:5)

这是我的样本:

private static final String KALIMAH = "\u0644\u064e\u0622 \u0625\u0650\u0644\u0670\u0647\u064e \u0625\u0650\u0644\u0651\u064e\u0627 \u0627\u0644\u0644\u0647\u064f \u0645\u064f\u062d\u064e\u0645\u0651\u064e\u062f\u064c \u0631\u0651\u064e\u0633\u064f\u0648\u0652\u0644\u064f \u0627\u0644\u0644\u0647\u0650";

protected void printGreeting (HttpServletResponse res) throws IOException {
    res.setContentType( "text/html" );
    res.setCharacterEncoding( "UTF-8" );
    PrintWriter out = res.getWriter();
    out.write( KALIMAH );
    out.close();
}