博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java 下载文件

Posted on 2021-09-28 16:47  生命如风  阅读(22)  评论(0编辑  收藏  举报
@SneakyThrows
    private void downFile(HttpServletResponse response, String path) {
        File file = new File(path);
        if (file.exists()) {
            InputStream ins = new FileInputStream(path);
            BufferedInputStream bins = new BufferedInputStream(ins);
            OutputStream outs = response.getOutputStream();
            BufferedOutputStream bouts = new BufferedOutputStream(outs);
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            int bytesRead;
            byte[] buffer = new byte[2048];
            while ((bytesRead = bins.read(buffer, 0, 2048)) != -1) {
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();

            ins.close();
            bins.close();
            outs.close();
            bouts.close();
        }
    }