Create a UTF-8 file using HttpServletResponse

I am trying to create a UTF-8 file "myFile.aaa" using HttpServletResponse (HttpServlet). The reason I need it to be UTF-8 is because it may contain special characters that cannot be printed. A.

However, the code below seems to create an ANSI-encoded file. At least this is what Notepad ++ says, and what I see is reading the characters 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(); } 
+7
source share
2 answers

You need to use the response character maker rather than the byte output stream.

Replace

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

by

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

In addition, I would recommend setting the content type to text/plain , and not too general, which implies binary content, not the content of the character.

I'm not sure about Notepad ++, but in Notepad, if a text document does not contain any characters beyond ANSI, it will be interpreted as ANSI. Do not be fooled by this behavior.

+11
source

Here is my example:

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

All Articles