Art*_*uro 7 servlets outputstream utf-8 character-encoding
我正在尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 12
您需要使用响应的字符编写器,而不是字节输出流.
更换
ServletOutputStream os = res.getOutputStream();
os.print("Hello World");
os.flush();
os.close();
Run Code Online (Sandbox Code Playgroud)
通过
res.getWriter().write("Some UTF-8");
Run Code Online (Sandbox Code Playgroud)
此外,我建议将内容类型设置为text/plain
,而不是一个过于通用的内容类型,它意味着二进制内容,而不是字符内容.
我不确定Notepad ++,但在记事本中,如果文本文档不包含ANSI范围之外的任何字符,它将被解释为ANSI.不要误导你这种行为.
这是我的样本:
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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17973 次 |
最近记录: |