【问题标题】:Create UTF-8 file using HttpServletResponse使用 HttpServletResponse 创建 UTF-8 文件
【发布时间】:2012-02-19 23:19:01
【问题描述】:

我正在尝试使用 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();
    }

【问题讨论】:

  • 为什么要在octet-stream 上指定charset

标签: servlets utf-8 character-encoding outputstream


【解决方案1】:

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

替换

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

通过

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

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

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

【讨论】:

    【解决方案2】:

    这是我的示例:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      相关资源
      最近更新 更多