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();
        }

    效果图:

  • 相关阅读:
    java第十三周作业
    java第十三周随堂
    安卓作业
    5.29 第十三周作业
    5.28第十三周上机练习
    5.22第十二周作业
    5.21第十二章上机练习
    5.15 第十一周作业
    5.14 第十一周 上机练习
    5.7第十周上机练习
  • 原文地址:https://www.cnblogs.com/wwj1992/p/6123727.html
Copyright © 2011-2022 走看看