zoukankan      html  css  js  c++  java
  • Java下载文件

     下面的代码简单的实现了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();
        }

    效果图:

  • 相关阅读:
    P1443 马的遍历
    P1747 好奇怪的游戏
    蜀绣
    Five hundred miles
    如果没有你
    Yellow
    流星

    深入理解计算机中的 csapp,h和csapp.c
    可迭代的集合类型使用foreach语句
  • 原文地址:https://www.cnblogs.com/wwj1992/p/6123727.html
Copyright © 2011-2022 走看看