java 文件下载

来源:互联网 发布:大腿内侧黑色素知乎 编辑:程序博客网 时间:2024/06/16 17:24

通过java程序,实现文件下载

public static void download(HttpServletResponse response, String filePathAndFileName)throws IOException {File file = new File(filePathAndFileName);if (!file.exists()) {return;}// 清空responseresponse.reset();// 设置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(file.getName(),"UTF-8"));response.addHeader("Content-Length",String.valueOf(file.length()));response.setContentType("application/octet-stream");ServletOutputStream op = response.getOutputStream();int bufferSize = 131072;FileInputStream fileInputStream = new FileInputStream(file);FileChannel fileChannel = fileInputStream.getChannel();ByteBuffer bb = ByteBuffer.allocateDirect(786432);byte[] barray = new byte[bufferSize];int nRead;int nGet;try {while ((nRead = fileChannel.read(bb)) != -1) {if (nRead == 0) continue;bb.position(0);bb.limit(nRead);while (bb.hasRemaining()) {nGet = Math.min(bb.remaining(), bufferSize);bb.get(barray, 0, nGet);op.write(barray);}bb.clear();}} catch (IOException e) {String info = "excel下载出错";logger.error(info,e);} finally {bb.clear();fileInputStream.close();fileChannel.close();}}

原创粉丝点击