首页 > 编程语言 > 详细

Java下载文件

时间:2016-12-02 00:55:20      阅读:293      评论:0      收藏:0      [点我收藏+]

 下面的代码简单的实现了java下载文件的步骤,看代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         
        //获取文件的类名
        String Path=this.getClass().getResource("/").getPath()+"JAVA笔记.txt";
        //对获取的路径进行解码
        Path=URLDecoder.decode(Path); 
        //获取文件名字和扩展名
        String FileName=Path.substring(Path.lastIndexOf("/")+1,Path.length()); 
        //设置输出文件名编码
        FileName=URLEncoder.encode(FileName, "UTF-8");
        //设置头信息
        response.setHeader("content-disposition", "attachment;filename="+FileName);
        response.setContentType("application/octet-stream");
        //获取文件流对象
        FileInputStream file=new FileInputStream(Path); 
        //定义字节数组,长度为文件流的长度
        byte[] buffers=new byte[file.available()];
        //获取输出流对象
        OutputStream writer=response.getOutputStream();
        //把流输出到字节数组中去
        file.read(buffers);
        //写到页面
        writer.write(buffers);
        //关闭流
        writer.close();
        file.close();
    }

效果图:

技术分享

 

Java下载文件

原文:http://www.cnblogs.com/wwj1992/p/6123727.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!