读取本地word 浏览器下载(设置编码格式)
String filePath = "C:\\word\\报告.doc"; BufferedWriter bos = null; BufferedReader bis = null; String fileName = year + "年" + month + "报告.doc"; try { char[] bytes = new char[1024]; String userAgent = request.getHeader("user-agent").toLowerCase(); if (userAgent.contains("msie") || userAgent.contains("like gecko")) { fileName = URLEncoder.encode(fileName, "UTF-8"); } else { fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } response.setContentType("Application/x-msdownload;charset=utf-8"); //告知客户端该文件不直接解析,采用附件形式打开 response.setHeader("Content-Disposition", "attachment;filename="+fileName); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); bis = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8")); bos = new BufferedWriter(new OutputStreamWriter(response.getOutputStream())); while (bis.read(bytes, 0, bytes.length) != -1){ bos.flush(); bos.write(bytes, 0, bytes.length); } } catch (IOException e) { e.printStackTrace(); }finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } }
如果是用常规的文件字节流读取本地的文件,下载下来的word总是打不开。只有用设置读取的格式为“utf-8”后,下载下来的word才能打开。