Create UTF-8 file using HttpServletResponse
Asked Answered
J

2

9

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();
    }
Jaynajayne answered 19/2, 2012 at 23:19 Comment(1)
Why would you want to specify charset on an octet-stream?Mccullers
V
16

You need to use the character writer of the response, not the byte output stream.

Replace

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

by

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

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.

Velasco answered 20/2, 2012 at 0:14 Comment(0)
P
7

Here is my sample:

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();
}
Promycelium answered 18/9, 2012 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.