java读取TXT文件显示在浏览器上,中文内容是乱码,求教~
代码如下。publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsSer...
代码如下。
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("fileName>>>" + fileName);
String filePath = "D://work//" + fileName;
File obj = new File(filePath);
if (!obj.exists()) {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print("指定文件不存在!");
return;
}
ServletOutputStream out = response.getOutputStream();
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ obj.getName().getBytes("GB2312"));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
} 展开
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("fileName>>>" + fileName);
String filePath = "D://work//" + fileName;
File obj = new File(filePath);
if (!obj.exists()) {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print("指定文件不存在!");
return;
}
ServletOutputStream out = response.getOutputStream();
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ obj.getName().getBytes("GB2312"));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询