使用 HttpServletResponse 创建 UTF-8 文件
我正在尝试使用 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();
}
I am trying to create a UTF-8 file "myFile.aaa" using HttpServletResponse (HttpServlet). The reason why I need this to be UTF-8 is because it might contain special non-printable characters.
However, code below seems to create ANSI-encoded file. At least that is what Notepad++ says, and what I can see reading chars from this file. What am I doing wrong?
Thanks
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用响应的字符编写器,而不是字节输出流。
替换
为
此外,我建议将内容类型设置为
text/plain
,而不是过于通用的类型,因为这意味着二进制内容,而不是字符内容。我不确定Notepad++,但是在Notepad中,如果文本文档不包含任何超出ANSI范围的字符,它将被解释为ANSI。不要用这种行为误导您。
You need to use the character writer of the response, not the byte output stream.
Replace
by
Further, I'd recommend setting content type to
text/plain
, not to an overly generic one which implies binary content, not character content.I'm not sure about Notepad++, but in Notepad, if the text document does not contain any characters beyond the ANSI range, it will be interpreted as ANSI. Don't mislead you by this behaviour.
这是我的样本:
Here is my sample: