简体   繁体   English

java中使用PrintWriter将国际字符写入HttpServletResponse时,显示为ä½ å¥½

[英]When International characters are written to HttpServletResponse in java using PrintWriter, it is displayed as 你好

When we write a chinese content which is got as response from a REST call to HttpServletResponse using PrintWriter as below, then, the issue occurs.当我们使用 PrintWriter 编写一个中文内容时,该内容是从 REST 调用 HttpServletResponse 得到的响应,如下所示,就会出现问题。 In the servlet when we use the below code, it gets downloaded as CSV.在 servlet 中,当我们使用以下代码时,它会以 CSV 格式下载。 The downloaded CSV has ä½ å¥½.下载的 CSV 有 ä½ å¥½。 Sample code which is used.使用的示例代码。

// Sample Chinese content got as response from REST call
String content ="你好";
response.setContentType("text/csv; charset=UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=Name.csv");

PrintWriter out = response.getWriter();
out.print(content);
out.flush();
out.close();

Could someone help in providing a way to print these characters as such in the csv file.有人可以帮助提供一种在 csv 文件中打印这些字符的方法。

The cause of this problem is the specification of Excel and Java.这个问题的原因是Excel和Java的规范。 Excel expects the CSV files are encoded in UTF-8 with BOM, while Java writes UTF-8 without BOM. Excel 期望 CSV 文件以带 BOM 的 UTF-8 编码,而 Java 编写不带 BOM 的 UTF-8。

As @VGR said in the comment, you have to add BOM ( \ ) at the top of the CSV file like this:正如@VGR 在评论中所说,您必须在 CSV 文件的顶部添加 BOM ( \ ),如下所示:

response.setContentType("text/csv; charset=UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=Name.csv");
response.getWriter().print("\ufeff");
response.getWriter().print("你好\n");
response.getWriter().print("再见\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM