java下载csv乱码问题
作者:互联网
一.问题。
用EXCEL打开文件时,总是产生乱码,但是用NOTEPAD++打开时,显示正常。然后,在NOTEPADD++的“格式”工具栏中查了一下文件编码,发现是“以UTF-8格式编码”。
二.解决方法。
以CSV方式导出的文件中默认不含BOM信息,通过给将要输出的内容设置BOM标识(以 EF BB BF 开头的字节流)即可解决该问题。追加BOM标识 outputStream.write(0xef); outputStream.write(0xbb); outputStream.write(0xbf);
三.完整代码。
@GetMapping(value = "/downloadFile",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public Object download(String id,HttpServletResponse response) { try { DataCleanManagement dataCleanManagement = dataCleanManagementService.getById(id); if (dataCleanManagement == null){ return ResultVO.fail("文件不存在"); } String path = config.filePath + File.separator + dataCleanManagement.getFilePath() + File.separator + dataCleanManagement.getResultFile(); File file = new File(path); // 以流的形式下载文件。 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header,给文件名进行utf-8编码,不然下载的时候文件名乱码不对 response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode (file.getName(), "UTF-8" )); response.addHeader("Content-Length", "" + file.length()); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/vnd.ms-excel;charset=gb2312"); outputStream.write(0xef); outputStream.write(0xbb); outputStream.write(0xbf); outputStream.write(buffer); outputStream.flush(); outputStream.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); log.info(e.getLocalizedMessage(),e); } return null; }
以上代码请供参考,如有不当,请及时指出!
标签:write,outputStream,java,dataCleanManagement,fis,乱码,new,csv,response 来源: https://www.cnblogs.com/aozhestudy/p/16650672.html