我有以下代码从文本文件中读取数据并打印到浏览器。 但是当它获得像“abc - abc”这样的数据时,它会在浏览器中显示垃圾字符,如“¬タモ”...... 可能是什么问题呢 ? fis指向文本文件。从文本文件中读取数据并写入浏览器。 thnx in advanced。
f = new File(URLDecoder.decode(filePathStr), URLDecoder.decode(fileName));
fis = new FileInputStream(f);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "-1");
res.setHeader("Cache-Control", "no-cache");
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
out = res.getWriter();
for (int i = fis.read(); i != -1; i = fis.read()) {
if (i == '\n')
out.print("</BR>");
else
out.write((byte) i);
}
答案 0 :(得分:0)
您的文件可能不是UTF-8。我会读取连接数组中所有字节的所有文件,然后用它创建一个字符串然后我会打印它。
答案 1 :(得分:0)
尝试手动输出类似
的内容out.print("υτφ-8 chars");
他们打印得正确吗?如果没有查看这篇文章How to get UTF-8 working in Java webapps?,请确保按照以下4个步骤操作如何在网页中显示UTF-8字符。
如果它们打印正确,则问题在于FileInputStream以及您如何读取文件。
您可以尝试以下
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
NEW UPDATE
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
File f = new File("C:\\TEST.TXT");
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
out = response.getWriter();
for (int i = isr.read(), k = 0; i != -1; i = isr.read(), ++k) {
if (i == '\n') {
out.print("</BR>");
} else {
out.write(i);
}
out.flush();
}
} finally {
out.close();
}
}
上面的代码应该可以正常工作,我已经测试了它